Welcome to Crystal Reports Development

Welcome! This section introduces you to developing with Crystal Reports, the world standard for desktop and web reporting, and provides you with an overview of the contents of this online help.

Click the appropriate link to jump to that section:

  • About Crystal Reports
  • About the online help
  • Command, button, and key conventions
Additional Resources

Seagate Software offers training for Crystal Reports and other Seagate Software products in major cities throughout North America and the world.

To view schedules and course descriptions or to schedule public or on-site training, visit our web site at:

http://www.seagatesoftware.com/coursedescriptions

Email us at training@seagatesoftware.com or call us at 1-800-877-2340 or 604-681-3435.

The Crystal Reports User's Guide is available in PDF format on the install CD in the Documentation folder. The contents of the online help includes everything from the printed manual, plus more.

Seagate Software Support web site

The Seagate Software Support web site, which serves as an extension of all Seagate Software products, is the place to go for product support, samples, educational documents, tutorials, tools, forums and more:

http://support.seagatesoftware.com

Seagate Software Developers Zone

The Seagate Software Developers zone is the key place for the latest development news. Updated weekly you will find this an invaluable resource on the latest features, issues, and tips and tricks.

http://www.seagatesoftware.com/products/dev_zone

Seagate Software IMG Holdings, Inc.
http://www.seagatesoftware.com
Support services:
http://support.seagatesoftware.com


About Crystal Reports

Crystal Reports is designed to work with your database to help you analyze and interpret important information. Crystal Reports makes it easy to create simple reports, and, it also has the comprehensive tools you need to produce complex or specialized reports.

Create any report you can imagine

Crystal Reports is designed to produce the report you want from virtually any data source. Built-in report experts guide you step by step through building reports and completing common reporting tasks. Formulas, cross-tabs, subreports, and conditional formatting help make sense of data and uncover important relationships that might otherwise be hidden. Geographic maps and graphs communicate information visually when words and numbers are simply not enough.

Extend reporting to the Web

The flexibility of Crystal Reports doesn't end with creating reports — your reports can be published in a variety of formats including Microsoft® Word and Excel, E-mail and even over the Web. Advanced Web reporting lets other members of your workgroup view and update shared reports inside their web browser.

Incorporate reports into applications

Application and web developers can save time and meet their users needs by integrating the report processing power of Crystal Reports into their database applications. Support for most popular development languages makes it easy to add reporting to any application.

Whether it's the web master in IT, the promotion manager in marketing, the database administrator in finance or the CEO, Crystal Reports is a powerful tool designed to help everyone analyze and interpret the information that's important to them.


About the online help

The online help includes technical information on the development tools included with Crystal Reports that allow you to integrate reporting into your application. The guide covers the Report Designer Component, the Crystal Report Engine API, the Crystal Report Engine Automation Server, and the Crystal ActiveX Control. It also contains tutorials and samples that will further aid you with adding the power of Crystal Reports to your application.

Click the appropriate link to jump to that section:

  • Section Contents
  • Using the online help
  • Command, button, and key conventions.


Section Contents

The following is a short description of each section in the online help.

What's New for Developers

With the release of Crystal Reports version 8.5 developers edition, Crystal Reports continues to improve the flexibility and power of the Report Designer Component, along with it's web reporting capabilities. New components and features allow you to enhance your users reporting experience and increase the availability of Crystal Reports.

This section introduces the new features and enhancements, which fall into three key cateories:

  • Report Designer Component (RDC)
  • Crystal Report Viewer Control
  • Web Reporting.

Key Features of Crystal Reports 8.x

This section highlights the key changes made for developers in versions 8 , and it points you to further information. For a more complete discussion of some of the more major changes, see A Closer Look at Some of the New Features.

Integration Methods

This section is to gives you an understanding of how integrating Crystal Reports into your applications has evolved. You will also learn the benefits of using the latest technology—represented in the Report Design Component (RDC). This technology will enable you to take full advantage of the powerful Crystal Report Print Engine and create the best applications available today.

Migrating to the RDC from the OCX

This section is to illustrates the benefits of using the RDC for integrating reporting functionality into your Visual Basic applications. Learn how to migrate applications from the OCX to the RDC to take advantage of the latest features within Crystal Reports. Also included is an overview of the RDC, its major components, object model, and a description of its advanced features not available within the OCX.

Introducing the Report Designer Component

This section introduces the Report Designer Component (RDC) and explains it's architecture along with some possible development scenarios. It also provides additional sources for help and information on the RDC, including sample applications that present the RDC in real-world scenarios.

Quick Start for using the RDC

This section helps you get started using the Report Designer Component (RDC) in Microsoft Visual Basic. Three examples provide you with the basic skills needed to use the RDC. You will find a high-level explanation of the steps required to add the RDC to a project, a tutorial on adding an existing report to the RDC, and a tutorial on creating and modifying a new report.

RDC Data Access

This section explains data access through the Report Designer Component (RDC), and describes how to connect to a data source through the Data Explorer. It also provides information on Active Data, the Microsoft Data Environment, and the database drivers used by the RDC.

Understanding the RDC Object Model

This section provides you with an understanding of the Report Designer Component (RDC) Object Model through a high-level overview of how a report is created. The overview is then related to the primary objects and collections contained in the RDC Object Model. More detailed information on a number of the objects, collections, and events is available at the end of the section.

RDC Programming

This section provides solutions to a number of common runtime challenges. Most of these challenges involve accessing an object and then changing the properties. The section first discusses special considerations when programming with the Report Designer Component (RDC); it then presents the two general methods to access an object in a report or subreport. The examples assume that you have used one of these methods to locate the object of interest in order to concentrate on the special considerations that you may have with each of the various procedures.

Programming the Crystal Report Viewers

The Crystal Report Viewer is a front-end user interface for viewing reports. In this section you will find detailed information on implementing the ActiveX and Java Bean viewers in your application.

Programming the Embeddable Crystal Reports Designer Control

This section demonstrates how to integrate the Embeddable Crystal Reports Designer Control (Embeddable Designer) into your application. Included are tutorials on creating sample applications in both Microsoft Visual Basic and Microsoft Visual C++. A brief section on creating reports in the designer at runtime is also included.

Working with Visual C++ and Visual InterDev

This section illustrates how the Report Designer Component (RDC) can be integrated using other development languages. Included are examples in Visual C++ and Visual Interdev.

Report Designer Component Object Model

The Report Designer Component is the ultimate development tool for your reporting needs. In this section you will find a detailed description of the Report Designer Component Object Model and its properties, methods and events.

Report Viewer Object Model

The Crystal Report Viewer contains an extensive object model allowing you complete control over how the viewer appears and functions. This section provides detailed information on the properties, methods and events of the Crystal Report Viewer object model for both the ActiveX viewer, and the Java Bean viewer.

Embeddable Crystal Reports Designer Control Object Model

The Embeddable Crystal Reports Designer Control (Embeddable Designer) is a new addition to the Report Designer Component; it enables you to provide a Crystal Reports designer in your application. In this section, you will find a general overview of the control as well as detailed information on its properties and methods.

Visual Basic Solutions

Crystal Reports offers you a wide range of solutions for your reporting needs. This section provides a general overview of the more common Crystal Reports development tools. These include the Crystal Report Engine API, Crystal ActiveX Control, and Crystal Report Engine Automation Server, but not the Report Designer Component. The Report Designer Component is the preferred Development tool and is described in previous sections.

Crystal Report Engine

The Crystal Report Engine is used alone and as a base class for other Crystal Reports development tools, including the Crystal ActiveX Control, Crystal Report Engine Automations Server, and the Crystal Visual Component Library. In this section you will find a general overview of how the Crystal Report Engine is used in an application, as well as a detailed section on the Crystal Report Engine API and it's most common functionality.

Crystal Report Engine Index

The Crystal Report Engine API is a powerful development tool for your reporting needs. In this chaptersection you will find detailed information on the functions, structures and constants of the Crystal Report Engine API. Syntax for the functions and structures is provided for C, Microsoft Visual Basic, and Delphi. In addition you will find a section on obsolete functions, structures, and constants, including a list of obsolete calls with the applicable replacement calls.

The Crystal Report Engine Class Library Reference

The Crystal Report Engine Class Library is based on the Microsoft Foundations Class Library, and provides an object oriented approach to programming the Crystal Report Engine in C++. In this section you will find detailed information on methods, structures and constants, along with a list of obsolete methods and structures.

Crystal Class Library for NewEra Reference

The Crystal New Era Class Library is a wrapper around the Crystal Reports Engine API created specifically for programming in the Informix New Era development environment. In this section you will find detailed information on classes and their associated methods, and constants.

Visual Basic Wrapper for the Crystal Report Engine

This section provides information on the functions and structures included in the Visual Basic wrapper for the Crystal Report Engine (Crwrap.bas). Special structures and functions have been created for Visual Basics native 4-byte alligned type.

Crystal Report Engine Object Model for the Automation Server

The Crystal Report Engine Object Library provides an object oriented approach for programming the Crystal Reports Engine in your application. In this section you will find detailed information on objects and collections, along with their associated properties, methods, and events.

Crystal ActiveX Control Reference

The Crystal ActiveX Control provides an easy to use interface for adding the basic functionality of Crystal Reports to your application. In this section you will find detailed information on properties, methods, and error messages.

Creating User-Defined Functions in C

Crystal Reports allows you to create User Defined Functions that are recognized by the Crystal Reports Formula Editor. In this section you will find detailed information on programming User Defined Functions in C.

Creating User-Defined Functions in Visual Basic

Crystal Reports allows you to create User Defined Functions that are recognized by the Crystal Reports Formula Editor. In this section you will find detailed information on programming User Defined Functions in Microsoft Visual Basic.

Creating User-Defined Functions in Delphi 3.0

Crystal Reports allows you to create User Defined Functions that are recognized by the Crystal Reports Formula Editor. In this section you will find detailed information on programming User Defined Functions in Delphi.

Code samples for the Crystal Report Engine Automation Server

This section provides code samples using the Crystal Report Engine Automations Server. The code samples are written in Visual Basic and can be easily incorprated into your applicaion.

Code samples for the Crystal Report Engine

This section provides code samples using the Crystal Report Engine. The code samples are written in C, dBASE, Delphi, and Visual Basic and can be easily incorprated into your applicaion.

Active Data

This section provides information on using active data in the Crystal Reports Development environment. Three areas are covered; the active data driver, Crystal Data Object, and Crystal Data Source Type Library. By reading these sections you will learn how to create active data reports, create recordsets, and connect to the datasource through the Report Designer Component automation server.

Crystal Data Source Object Models

Crystal Reports provides support for reporting off data when no true data source exists. In this section you will find detailed information, including properties and methods, on Crystal Data Objects and the Crystal Data Source Type Library.

The Crystal Active Data Driver Reference

This section provides information on the functions available in the Active Data Driver (P2smon.dll). These functions simplify the creation of Data Definition Files and allow you to pass a recordset to a report using the Crystal Report Print Engine.

Appendix A: International Office Directory

This appendix provides contact information by region. For technical support information, see the Technical Support Guide.


Using the online help

Crystal Reports online help includes all topics within the user's guide. It also provides additional reference material ranging from specific information on the function of a button to general information on how to create a report formula based on a sample business scenario.

Locate information quickly

Access online help from the Crystal Reports help menu.

Use the Contents tab to view all major sections in the online help and drill down to specific headings within each section, the Index tab to view topics in alphabetical order, and the Search tab to enter a keyword to view all the sections that relate to the keyword.

Sample Reports

Many topics in the Crystal Reports online help include a list of related sample reports. Use these reports to illustrate concepts the topic describes. The sample reports can be adapted to your own needs.

Sample reports are located in the Crystal Reports directory under \Samples\En\Reports.

Product registration

There are several ways you can register your product:

  • Fill out the Product Registration form on the Seagate Software web site at:

    http://www.seagatesoftware.com/register

  • Use the Registration Wizard accessible from the Product name program group.
  • Print the Product Registration form and then fax it to the Registration fax number closest to you. Seagate Software will then fax you a registration number that can be entered into the product the next time you use it.

    Registration Fax Numbers

    USA/Canada +1 (604) 681-5147
    United Kingdom +44 (0) 20 8231 0601
    Australia +6 2 9955 7682
    Germany +49 (0) 69 9509 6182
    Hong Kong +852 2893 2727
    Singapore +65 777 8786

Registration is required to access online or telephone technical support. In addition, registering the product will ensure that you are kept up-to-date with product advancements.

Technical Support

To find out how to receive technical support services on the product you purchased:

  • Consult the enclosed Technical Support Guide.
  • Go to our support website at http://support.seagatesoftware.com.
  • Contact your regional office. See the International Office Directory.


Command, button, and key conventions

The online help uses the following conventions:

Commands and buttons

For easy recognition, command names and button names are displayed in bold. For example: New command, Print button, etc.

Key combinations

Keyboard shortcuts appear in the following forms:

  • Delete means the Del key (either the Delete key, or the Del key on your numeric keypad).
  • Enter means the Enter or Return key, depending on which of these keys appears on your keyboard.
  • Ctrl-Key, Shift-Key, and Alt-Key are examples of the notation for two-key combinations. Press the first key in the combination (Control, Shift, or Alt), and, at the same time, press the second key in the combination (designated above as Key). For example: Ctrl-C means to hold the Control key down and then press the letter C on your keyboard (Ctrl-C is the Windows Copy command).

Other conventions

Courier font indicates data that you enter using the computer keyboard. It is also used to show sample code: CRViewer1.ReportSource = CRXReport.


What's New for Developers

With the release of Crystal Reports version 8.5 developers edition, Crystal Reports continues to improve the flexibility and power of the Report Designer Component, along with it's web reporting capabilities. New components and features allow you to enhance your users reporting experience and increase the availability of Crystal Reports.

This section introduces the new features and enhancements, which fall into three key cateories.

  • Report Designer Component (RDC)
  • Crystal Report Viewer Control
  • Web Reporting.

Click the appropriate link to jump to that section:

  • Web Reporting
  • Report Designer Component 8.5 (RDC)
  • Crystal Report Viewer


Web Reporting

To better meet your web reporting needs, Crystal Reports now integrates fully with Crystal Enterprise, a web-based report management tool that works within your company's existing web infrastructure.

If you purchased the Professional or Developer edition of Crystal Reports, then you also received the Crystal Enterprise Standard CD. This additional CD is included in the box with Crystal Reports, along with five free concurrent access licenses of Crystal Enterprise Standard.

Click the appropriate link to jump to that section:

  • Increased value of the Crystal Enterprise Web Component Server
  • Complete XML support for the Web
  • Improved interactivity with parameters
  • Customizable DHTML Report Viewer
  • Display web reports independent of server location
  • Extend reporting abilities with additional applications
  • Improved interactivity with parameters


Increased value of the Crystal Enterprise Web Component Server

Use the newly re-designed and enhanced Web Component Server (WCS) from Crystal Enterprise to power your web-reporting solution and to replace the older WCS from Crystal Reports 8. Crystal Enterprise Standard provides significant improvements and enhancements over the version 8 WCS.

Run the Web Component Server on any machine

Install the Crystal Enterprise Standard CD on whichever machine you want to coordinate your web reports. With Crystal Enterprise Standard, you no longer need to install and run Crystal Reports and the WCS on your web server.

If you need a reporting solution with greater scalability, use Crystal Enterprise Professional, which can be installed on as many machines as are necessary (whereas Crystal Enterprise Standard is limited to installation on a single machine). Further, with Crystal Enterprise Professional, you can specify the server pieces you want running on each machine.

Scale your reporting framework to meet increasing demands

Crystal Enterprise provides you with a scalable, web-based solution for managing the access and delivery of hundreds or thousands of mission-critical Crystal reports to every decision-maker—across the enterprise and beyond.

As your company's web reporting needs increase, you can upgrade seamlessly to Crystal Enterprise Professional without having to reinstall; you can also add more licenses and components so that Crystal Enterprise grows right along with you.

Schedule reports to maintain up-to-date information

Schedule important reports to run on a regular basis so that everyone has access to the most current information about your enterprise.

Publish reports to the Web in seconds

With just a few easy steps, you can publish your reports to the Web for viewing by all with the Report Publishing Wizard.

Manage folders for sharing reports

Share reports across the enterprise or across the Web by publishing them to the default Guest favorites folder on the Automated Process Scheduler (APS). Users can also publish to other folders, as determined by the Administrator.

Administer easily from one central console

By consolidating administrative tasks, the Crystal Management Console (CMC) makes administering your web reporting solution quick and easy—regardless of the size of your enterprise.

Use the CMC to gain immediate control over what can or cannot be seen, run, or managed by everybody. You define all users' viewing and managing privileges for particular reports.

Integrate Crystal Reports performance with existing IT investments

Trust your Crystal web reporting solution to work to its full potential with your existing web server investment.

Crystal Enterprise Standard has improved web server support, including compatibility with Domino web servers through DSAPI interface, and Apache servers through a DSO (Dynamic Shared Object) module on Solaris and Linux. Crystal Enterprise Standard also supports CGI on Solaris and Linux.

Use scripting on the Crystal Enterprise WCS

The Crystal Enterprise Web Component Server now provides complete support for scripting.


Complete XML support for the Web

Crystal Reports now fully supports the Extensible Markup Language (XML) adopted by the World Wide Web Consortium (W3C) for delivering content over the Internet.

XML is emerging as the standard data format for the whole data-related industry because it's recognized across applications and across platforms. Keeping pace with the current advance in technology, Crystal Reports allows you to report off existing XML data and to export your work to XML format.


Access XML data at runtime

Use the Report Designer Component to access XML data streams at run time and pass that information to objects in report applications.

Note: For information on using XML, refer to the new "XML" chapter of the Crystal Reports User's Guide.

Export report data straight to XML

Export your report data to XML format quickly at runtime. This allows you to send the data to other eCommerce applications used to read and manipulate information.

New properties have been added to the ExportOptions object to support these new features. These properties are:

  • XMLAllowMultiplePages
  • XMLFileName

Note: For more information see ExportOptions Object Properties.


Improved interactivity with parameters

Using parameters not only enables user-driven reporting, but also increases report performance, especially over the Web. Create multi-purpose reports to ensure that everyone receives the right information quickly.

All of Crystal Reports' web-enabled report viewers have been improved to allow report designers and end users to utilize parameters to their full potential over the Web. Whether users prefer the Java, ActiveX, or DHTML viewers, they can interactively regulate the information they see by accepting default report parameters, picking from listed options, specifying multiple values, or entering ranges.


Customizable DHTML Report Viewer

Customize the Crystal Reports Dynamic HTML viewer to integrate seamlessly with the design of an existing eCommerce web site or corporate intranet. The DHTML viewer exposes the operations of its toolbar (via JavaScript), thereby giving report designers the ability to customize both its workings and its look-and-feel.

The enhanced DHTML viewer is so flexible that users can view reports, drill down on charts, link to on-demand subreports, or quickly export valuable data—all without even seeing that their experience is powered by Crystal Reports.


Display web reports independent of server location

Use Relative URLs to share your reports and their associated report objects on any server, in any directory. Each report remains independent of its actual location, because Relative URLs eliminate dependence upon any particular server or virtual directory.


Extend reporting abilities with additional applications

With Crystal Enterprise Standard, use the ePortfolio, other samples, or any client application designed by your Administrator (using the SDK) to access shared reports.


Additional Web reporting features

HTML and DHTML export

The performance of the HTML and DHTML export has been greatly improved.

Re-distribute the ASP Web Report Server

The enhanced ASP Web Report Server (rptserver.asp) is no longer dependent upon the Web Component Server, so developers can easily distribute their ASP web applications.

Note: For information on redistribution rights refer to License Manager Help (License.hlp) .

Facilitate administration with the license manager

Keep track of your Crystal Reports licenses and key codes with the License Manager (available only with Crystal Reports Developer Edition). This new administrative tool makes it easy for you to ensure that your product installation always meets your reporting needs. It also allows you to check the number of concurrent user licenses being used in the ASP environment. Access the License Manager from the Crystal Reports Tools program group on the Start menu.

Please note that the Report Designer Component will work only within the concurrent license limit when used as a reporting server.

Note: For more information see "Licence Manager" in the License Manager Help (License.hlp).


Report Designer Component 8.5 (RDC)

Designed for Microsoft Visual Studio and other COM-based development environments, the feature-rich Report Designer Component 8.5 (RDC) gives developers unprecedented control over report layout and formatting for web and Windows application reporting.

Reflecting the enhanced features of the Crystal Report Engine, the RDC now supports most of the new Crystal Reports features, including PDF export, XML export and data access, alerting, summaries for hierarchical groups, and many more.

Click the appropriate link to jump to that section:

  • Embed a Crystal Reports Designer in your application
  • Create and modify Report Alerts
  • Re-import subreports
  • Summarize on hierarchical data
  • Export to paginated PDF, and paginated RTF


Embed a Crystal Reports Designer in your application

Your users can now design or edit reports at runtime with the Embeddable Designer. This easy-to-use ActiveX control provides the full power of Crystal Reports to your application. The control is placed on a form, or in a container within the form, and displays a new or existing report in design mode. This presents the user with an interactive environment in which to design or edit the report. The Embeddable Designer allows users to:

  • add data sources
  • add database fields
  • create and add formulas
  • create and add parameters
  • group data
  • summarize data
  • add charts
  • add subreports
  • add special fields
  • format fields and sections.

Note: For more information see Embeddable Crystal Reports Designer Control Object Model, and Programming the Embeddable Crystal Reports Designer Control.


Create and modify Report Alerts

Report Alerts are custom messages created in either the Crystal Reports Designer, the Report Designer Component, or the Embeddable Crystal Reports Designer Control. Report Alerts may indicate action to be taken by the user or information about report data. For more information see Report Alerts in the Crystal Reports User's Guide.

Two new collections and two new objects have been added to the RDC object model to allow you to create, modify, and monitor Report Alerts at runtime. These collections and objects are:

  • ReportAlerts Collection
  • ReportAlert Object
  • ReportAlertInstances Collection
  • ReportAlertInstance Object.


Convert database drivers

The data source your report is pointing to can now be changed at runtime by converting the database driver. You can have this change reflected immedialtely in your application, or save the report, and have the change take effect the next time it is refreshed.

For more information see the ConvertDatabaseDriver Method (Database Object).


Re-import subreports

Subreports can be newly created in the main report or imported from an existing report file. If the subreport is imported from an existing report file, it can be re-imported at runtime using the ReImportSubreport method. When previewed, printed, or exported, a re-imported subreport will reflect all changes made to the formatting, grouping, and structure of the existing report file.

For more information see the ReImportSubreport Method (Subreport Object).


Summarize on hierarchical data

Make large, complex data sets easier to understand than ever by taking advantage of the new ability to create Subtotals, Grand Totals, and Summary fields for hierarchical groups: to do so, select the "Sum across hierarchy" option, which has been added to the Insert Subtotal, Insert Summary, Insert Grand Total, and Change Summary dialog boxes.

Hieracrchical summaries can be enabled at runtime through the HierarchicalSummaryType property. This property has been added to the following two objects:

  • RunningTotalFieldDefinition Object
  • SummaryFieldDefinition Object.


Export to paginated PDF, and paginated RTF

Export your reports—in whole or in part—directly to the popular Portable Document Format (PDF), and then distribute these reports by email, over the Web, or in print. Alternatively, take advantage of the new Rich Text Format (RTF) exporting feature, which is based on the Crystal Reports Encapsulated Page Format (EPF).

In addition, Crystal Reports now supports page ranged export to PDF and RTF formats.

New properties have been added to the ExportOptions object to support these new features. These properties are:

  • PDFExportAllPages
  • PDFFirstPageNumber
  • PDFLastPageNumber
  • RTFExportAllPages
  • RTFFirstPageNumber
  • RTFLastPageNumber.

Note: For more information see ExportOptions Object Properties.


Crystal Report Viewer

An integral part of the Report Designer Component, the Crystal Report Viewer offers full control over the previewing of reports in both client and Web environments. A new freeze pane feature and improved distribution further enhance the viewer's functionality.

Click the appropriate link to jump to that section:

  • Freeze panes in the Crystal Report Viewer
  • Improve runtime distribution


Freeze panes in the Crystal Report Viewer

The ActiveX viewer now has a feature similar to the Freeze Pane feature found in Microsoft Excel. In the ActiveX Viewer, right-click and select Freeze Pane from the shortcut menu to freeze the report from the bottom-right corner of the selected object. Unfreeze using the same menu. Scroll horizontally or vertically, and the report data scrolls as it would in Excel: vertical scrolling scrolls the portion of the report to the right of the selected object (above and below); horizontal scrolling scrolls the portion of the report below the selected object (left and right of the object).


Improve runtime distribution

Distribution of the Crystal Report Viewer (Crviewer.dll) has been simplified.Crviewer.dll is no longer dependent on the Urlmon.dll making for an easier installation of the RDC with your application.


Additional information

Crystal Reports product news

http://www.seagatesoftware.com/products/crystalreports/

Crystal Reports demos

http://www.seagatesoftware.com/products/crystalreports/showme/

Crystal Enterprise product news

http://www.seagatesoftware.com/products/crystalenterprise/

Product information

http://www.seagatesoftware.com/products/

Developer Zone

http://www.seagatesoftware.com/products/dev_zone/

Online support, samples and tech briefs

http://support.seagatesoftware.com/homepage/

Training and consulting

http://www.seagatesoftware.com/services/

Seagate Software homepage

http://www.seagatesoftware.com/homepage/


Key Features of Crystal Reports 8.x

This section highlights the key changes made for developers in versions 8 , and it points you to further information. For a more complete discussion of some of the more major changes, see A Closer Look at Some of the New Features.

Click the appropriate link to jump to that section:

  • Report Integration controls for Visual InterDev
  • Lotus Domino sample applications
  • Enhancements to the Report Designer Component
  • API Enhancements from Crystal Reports 7 or earlier
  • A Closer Look at Some of the New Features


Report Integration controls for Visual InterDev

The Report Integration controls allow Web developers using Microsoft Visual InterDev 6.0 to write Web applications that generate Crystal reports hosted on either a Web Reports Server or an ASP server. End users of these applications would then view these reports using a Report Viewer running on a browser.

You control such things as logging on to database servers, prompting of parameters and specifiying selection formulas in these reports. You allow your users to view reports using either the Report Viewer for Java or the Report Viewer for ActiveX. You can also decide which properties to enable for the end user within the Report Viewer (printing or exporting, for example).


Lotus Domino sample applications

If you're using Crystal Reports in conjunction with Lotus Domino, see the new Lotus Domino sample applications. These documents demonstrate how Crystal Reports increases the value of your Lotus Domino investment.

If you followed the default installation, you should find the sample documents in your Program directory (usually C:\Program Files\Seagate Software\Crystal Reports\Samples\En\Reports\Lotus Domino). You can also serve these reports up from within a Lotus Notes application by opening either Crazev6.nsf or Xglobal.nsf from within Lotus Notes.


Enhancements to the Report Designer Component

The Report Designer Component has seen the most changes including:

CRPE API

Report Variables

Set OLE Object Location

Save Preview Picture

Charts

Creating Reports at runtime using code

Cross-Tab reports

ADO and OLEDB Tables

Data Explorer

Select Distinct Records

Selecting & Editing Embedded Fields

Report Object Events

Formatting

Formulas

Grouping

IDE


CRPE API

More of the CRPE API functionality is now available through the RDC.

The following new interfaces have been added:

  • ITableLinks
  • ITableLink
  • IFieldDefinitions
  • IObjectSummaryFieldDefinitions
  • ICrossTabGroups
  • ICrossTabGroup
  • ISubreportLinks
  • ISubreportLink

The following have been added to existing interfaces:

  • IDatabase
  • IDatabaseTables
  • IDatabaseTable
  • IFormulaFieldDefinitions
  • ParameterFieldDefinitions
  • ISQLExpressionFieldDefinitions
  • IRunningTotalFieldDefinitions
  • ISummaryFieldDefinition
  • IRunningTotalFieldDefinition
  • IReport
  • ISections
  • ISection
  • IGraphObject
  • ICrossTabObject


Report Variables

Certain events, such as the OnSectionFormat event, may get fired more than once in a section. For example, a Details section may fire multiple times for a given record if the program is performing "Keep Section Together" calculations for the report. When you use VB variables that are supposed to increment once for each record (for example, when you calculate a running total), you can have problems maintaining state with these multiple firings.

To prevent these problems, the RDC now enables you to declare Report Variables. Report Variables are Crystal variables that you can use in your VB code. Report Variables "understand" what's going on in the report and they increment appropriately. This enables you to do more of your coding than ever in VB and still get the results you expect. For more information, see Using Report Variables.

To support report variables, the methods AddReportVariable, GetReportVariableValue and SetReportVariableValue have been added to the IReport interface.


Set OLE Object Location

You can now set the location of an OLE object at runtime using the new method, SetOleLocation, under the ICROleObject interface. This also enables you to change an OLE object to point to different files at run time including image files.

The existing method, SetFormattedPicture, is still supported. However, if you use both SetFormattedPicture and SetOleLocation, SetFormattedPicture overrides SetOleLocation.

Also note that if an OLE object is in the Detail section and you call SetOleLocation in the OnFormat event for every detail record, this will affect your performance significantly.


Save Preview Picture

In the Crystal Report Designer, you now have the option to save a snapshot of the first page of a report for previewing in the File Open dialog box. This capability is supported in the RDC.

Two methods have been added to the Report Designer Component runtime under the IReport interface: get_SavePreviewPicture and put_SavePreviewPicture. You can use get_SavePreviewPicture to get the property and use put_SavePreviewPicture to set the property.

Note: You should be very careful to enable this flag at design time. If you don't and if the report contains thumbnail pictures, it can affect the performance when saving or loading the report.


Charts

The following charting enhancements are carried through the Crystal Report Designer and the Report Designer Component:

Automatically Scale Data Axis

Two new runtime properties have been added under the class GraphObject: EnableAutoScaleDataAxis and EnableAutoScaleData2Axis.

Legend Enhancements

In the Report Designer Component runtime, the new enumerator type CRPieLegendLayout has been added, and the new property LegendLayout has been added under the class GraphObject.

Chart on All Records

Please refer to the Crystal Reports User's Guide for a detailed description of this feature.

Chart on Running Totals

Please refer to the Crystal Reports User's Guide for a detailed description of this feature.

Default Titles for Charts

Previously, when you used the Report Expert to create a chart, the expert assigned a title to the chart unless you specified one. Now the expert supplies the following titles by default: title, subtitle, footnote, group title, data title, data2 title and series title.

To support these enhancements, the following new properties have been added to the GraphObject class for the Report Designer Component runtime:

  • IsTitleByDefault
  • IsSubTitleByDefault
  • IsFootnoteByDefault
  • IsGroupTitleByDefault
  • IsSeriesTitleByDefault
  • IsDataTitleByDefault
  • IsData2TitleByDefault

Font Change for Chart Elements

You may now change the font used for chart elements. In the Report Designer Component runtime, properties have been added to the GraphObject class to change the font for these chart elements: title, subtitle, footnote, group title, data title, series title, legend, group labels, data labels and series labels.

New Formats for Data Points and Data Axes in Charts

Four new formats have been added to the Chart Expert to format data point values and data axis values: 1K, 1M, $1K and $1M.

In the Report Designer Component runtime, the following properties have been added to the GraphObject class to support this:

  • DataAxisNumberFormat
  • Data2AxisNumberFormat.

Creating Charts Based on a Cross-Tab

You may now create a chart based on a cross-tab object. A new method, AddGraphObject, has been added with the parameter pCrossTabObject. pCrossTabObject is optional, is a VARIANT type, and has to be a CrossTabObject. (For crGroupGraph and crDetailGraph, this parameter is ignored.)


Creating Reports at runtime using code

The RDC now includes Report Creation API methods. These methods enable you to create ad hoc reports at runtime using nothing but code. The methods can be used within Visual Basic, Microsoft Office, or in any environment from which you can access an automation server. Because these methods now enable Crystal Reports Designer functionality in your runtime applications, they require separate licensing.


Cross-Tab reports

Cross-Tab Formatting

The enhancements to the Crystal Report Designer for formatting cross-tabs (for example, predefined grid styles, formatting separate grid lines) are now also available in the Report Designer Component at design time.

Selecting & Formatting Cells in Cross-Tabs

You may now select individual cells in a cross-tab, or select multiple cells in a cross-tab, to format and re-size them. This is a design-time only feature.


ADO and OLEDB Tables

Two new methods have been added under the IDatabase interface to give you more control when working with ADO and OLEDB data:

  • AddADOCommand (connection, command)
  • AddOLEDBSource (connection, tableName)

These two methods enable you to add an ADO and OLE DB data source, save the report, and then refresh the report.

The methods from earlier versions, SetDataSource and Add (under IdatabaseTables) allow you to set a run time ADO record set as a data source, but the report saved will not be refreshed.


Data Explorer

The Report Designer Component has been enhanced to use the Data Explorer when you:

  • use a Crystal Report Designer driver to create a report through the Report Expert,
  • perform a Set Location, or
  • perform an Add Database.

When you create a report or do a set location, you now use the new Data Explorer to manage your database connections. The Data Explorer provides an integrated tree view of all data sources available to you.

For more information on the Data Explorer, please refer to Crystal Reports User's Guide.


Field Explorer

The Field Explorer has been enhanced. It now includes an Unbound Fields node.

Unbound Fields

The RDC now enables you to create report templates based on unbound field objects. Then, using minimal code, you can bind those field objects to a data source (or one of several data sources) at runtime. The Report Engine uses the data type and the Name property of the unbound field object to match it with a data field in the recordset.

This functionality makes it easy to build reporting into n-tier applications where you have on-demand recordsets and non-continuous data connections. It also makes it easy to build a single report that can work with a variety of recordsets, making development and maintenance more efficient.

Unbound fields allow for great flexibility, since you can easily change the data source for an unbound field at runtime.

  • In the Visual Basic RDC design time environment, you can easily add unbound fields to your report by dragging and dropping any of the unbound field types from the Designer's treeview onto the report.
  • In the Report Designer Component runtime, you can add an unbound field object to a section using the new function AddUnboundFieldObject under the Section class.
  • To bind the unbound field to a database field at runtime, you can use the new method SetUnboundFieldSource.
  • Alternatively, you may use automatic unbound field binding, based on either the field name or the field name and value type of the field in the data source. To do so, you would use the new method AutoSetUnboundFieldSource, and specify one of the constants crBMTName or crBMTNameAndValue for CRBindingMatchType.


Select Distinct Records

You may now direct the RDC to select only unique records from a data source. In the IReport interface, EnableSelectDistinctRecords has been added to allow you to get or set this option based on user input.


Selecting & Editing Embedded Fields

If a database field is embedded in a text object, you can now select and edit the embedded objectfield as if it were not embedded. Note that the RDC allows you to manipulate embedded objects at design time only.


Report Object Events

BeforeFormatPage & EndFormatPage Events

The BeforeFormattingPage and EndFormattingPage events are fired before and after formatting a page respectively. These events enable you to make a variety of page-specific changes to your report.

You could, for example, reset Report Variables that you were using to calculate a subtotal on a page-by-page basis. Another possibility is to control the report formatting information as desired before the page is formatted.

Note: There are a number of properties and methods you cannot use in these events. For example, you cannot use the "SetText" method in BeforeFormatPage or EndFormatPage or you will get a runtime error. When the events are fired, the report is in Active formatting mode while the sections are in inactive formatting mode. Thus, you can use properties and methods that affect the report object, but you can't use properties and methods that affect anything in the sections of the report.


FieldMapping Event

The FieldMapping event is fired if a database is changed while verifying database. Field mapping enables you to change the name of a database field that a report field points to if that field no longer exists or has been renamed in the data source. Verifying the database or using SetLocation will trigger the FieldMapping event.

Note: This event is fired only when the fieldmapping type is not set to automatic. If it is set to automatic (the default setting), the program will display a field mapping dialog box instead.


NoData Event

The NoData event is fired when the data set in the report is empty. It enables you to stop the processing and/or invoke error handling.

Note: This event is fired only for the main report even if there is a subreport.


Formatting

Text Formatting

To complement the enhancements in the Crystal Report Designer on line spacing, character spacing, text rotation and indentation for text objects and string field objects, the Report Designer Component runtime has also been enhanced in the following ways.

In the ITextObject interface for text objects, and the IFieldObject interface for string field objects, these properties and methods have been added:

  • CharacterSpacing (read/write)
  • LineSpacing (read)
  • LineSpacingType (read)
  • SetLineSpacing (method)
  • TextRotationAngle (read/write)
  • FirstLineIndent (read/write)
    When reading, this method gets first line indent of the first paragraph; when writing, it sets first line indent for all the paragraphs.
  • LeftIndent (read/write)
    When reading, this method gets the left indent of the first paragraph; when writing, it sets the left indent for all the paragraphs.
  • RightIndent (read/write)
    When reading , this method gets the right indent of the first paragraph; when writing, it sets the right indent for all the paragraphs.
  • TextFormat (read/write)
    For text objects only.


Fractional Point Font Support

You may now specify a fractional point size for text objects and database fields, including the 10.5 point font commonly used in Japanese. To do so, type in a fractional point size in the Font tab of the Format Editor that you use to format a selected text object or database field.

Note: VB users cannot use this feature. While our own dialog box now supports fractional point sizes, Visual Basic does not support such sizes.


Accounting Conventions

To support conventions used in accounting, you may now control how the negative symbol, currency symbol and zero value are displayed, and reverse the sign when displaying numbers in accounting reports. To implement these conventions, the following properties have been added to the Report Designer Component runtime FieldObject class: UseReverseSign and ZeroValueString.


Formulas

Basic Syntax

The formula language in Crystal Reports 8 has been extensively enhanced with the addition of a new Visual Basic-like language called Basic syntax. It is an alternative to the formula language. Most new functions, operators, and control structures have been added to both Crystal and Basic syntaxes, and most existing Crystal capabilities have been duplicated in Basic as well. While existing Crystal Reports users do not have to learn this new syntax to utilize the extra capabilities, it is intended to be easy to learn and use for developers already familiar with Visual Basic.

Apart from the new functions, operators and control structures available in both syntaxes, Visual Basic developers who distribute applications can benefit from the fact that Basic formulas are portable and do not require any additional DLL's to run.

You must use a single syntax within a given formula, but you may use formulas with different syntaxes in the same report. When you enter a formula (other than a selection or search formula - see note below) in the Formula Editor, you can choose either Crystal or Basic syntax as the default syntax for the formula.

New functions available to both syntaxes include:

  • financial functions
  • mathematics functions
  • programming shortcut functions
  • type conversion functions
  • date and time functions
  • array and string functions
  • percentage functions.

New operators available to both syntaxes include:

  • integer division
  • exponentiation
  • eqv
  • imp
  • xor
  • mod.

New control structures available to both syntaxes include:

  • for statement
  • do statement
  • select ... case statement

For a more detailed description of these functions, operators and control structures, please refer to the Crystal Reports Online Help (crw.chm).

Note: The two syntaxes are fundamentally equivalent, with one exception: When you create or modify search or selection formulas using the Select Expert, the Search Expert, or the Formula Editor, you can only use Crystal syntax.


FormulaSyntax and LastGetFormulaSyntax

Two new properties have been added to the Report class for working with these two languages: FormulaSyntax and LastGetFormulaSyntax.

  • You can specify the syntax that you want to use before you create a formula via the FormulaSyntax property.
  • After getting formula text, you can use the property LastGetFormulaSyntax to determine the syntax used for the formula.


Grouping

Hierarchical Reporting

You may now use hierarchical grouping to arrange data in a report to show hierarchical relationships. You still keep all the elements of the hierarchy in the same table, but you can now display the relationships between the elements. This can be useful, for example, when reporting off a Human Resources database, to show the organizational hierarchy within a company.

In the Report Designer Component runtime, the following properties have been added to implement this grouping under the Area class:

  • EnableHierarchicalGroupSorting
  • ParentIDField
  • InstanceIDField
  • GroupIndent.

You can use the InstanceIDField and ParentIDField properties to organize the group sorting tree, use the GroupIndent property to design the layout, and use the EnableHierarchicalGroupSorting property to enable or disable hierarchical group sorting.

At design time you may select hierarchical grouping for your report in the Report Designer Component, by right-clicking and choosing Report|Hierarchical Grouping Options. This will invoke the Change Hierarchical Options dialog box.

For more information and an example of how to use this feature, please refer to the Crystal Reports User's Guide.


IDE

Toolbars

As in the Crystal Report Designer, toolbars now have an updated, flattened look, and can be moved. And, in particular to the Report Designer Component, the toolbars can also be resized to fit your needs.


API Enhancements from Crystal Reports 7 or earlier

Those enhancements that correspond with Crystal Reports 7 or earlier versions include the following:

Tool Tips

Show Object Names for Fields

MTS Support

OLAP Grid Formatting

Exporting to Excel 7.0 and 8.0 Formats

Save As Version 7 Format

Optimized Group Tree Creation & Deletion

Printing

Searching

Summarizing

Viewer

Web


Tool Tips

There are now tool tips for objects in the RDC design time that display the data type, object name, and field name for the object wherever applicable.


Show Object Names for Fields

In the RDC design time, you may now choose to display the object name for a field (the Name property as it appears in the VB Properties Window. You can set this option on the Layout tab of the Default Settings dialog box.


MTS Support

The RDC runtime supports the apartment model (apartment threading) and can thus run under Microsoft Transaction Server (MTS). It does not support state free status, however, which means it cannot utilize certain MTS functionality.

When you install a component within MTS, MTS allocates a Transaction Support property that defines the way the component will behave. The property has four settings:

  • Requires a transaction.
  • Requires a new transaction.
  • Supports transactions.
  • Does not support transactions.

Because the RDC does not support state free status, when you install it to work within MTS, make certain you choose the "Does not support transactions" setting. This makes certain that the component will never attempt to run within a transaction. It will always run outside the transactions.

Note: RDC only supports MTS in ASP8. Therefore, you cannot use MTS in VB.


OLAP Grid Formatting

You may now import a report with an OLAP grid, select the grid and format it. When you right-click the grid, you can select Cut, Copy, or Format from the shortcut menu. If you choose Format, the program invokes the Format Editor with the Common and Border tabs.


Exporting to Excel 7.0 and 8.0 Formats

You may now export to Excel 7.0, 7.0 Extended, 8.0 and 8.0 Extended formats from the Report Designer Component runtime.

Now, under the IExportOptions interface, there are four new formats:

  • crEFTExcel70
  • crEFTExcel70Tabular
  • crEFTExcel80
  • crEFTExcel80Tabular

There are also six new Excel format option properties:

  • ExcelTabHasColumnHeadings
  • ExcelUseWorksheetFunctions
  • ExcelConstantColumnWidth
  • ExcelAreaType
  • ExcelAreaGroupNumber
  • ExcelUseTabularFormat

You can also export now to PDF and HTML 4.0 formats.


Save As Version 7 Format

The report file format has been changed in Crystal Reports 8.

  • In the Report Designer Component design time, you now have the option of saving the report in Version 7 or Version 8.
  • In the Report Designer Component runtime, there is a new method under the IReport interface, SaveAs, that allows you to specify in which file format (Version 7 or Version 8) you would like to save your report.

The previously used method Save is now hidden.

Note: Not all Version 8 reports can be saved in Version 7 format and still work properly. Reports containing the following features will not work properly in Version 7 format:

    • Formulas using the new Basic syntax
    • Formulas using new formula functionsReports created off OLE DB data source, especially if they use the extended style
    • Hierarchical grouping
    • Percentage summary fields


Optimized Group Tree Creation & Deletion

Group tree creation and deletion at runtime have been optimized. Now you can begin viewing the first page of the report or navigating the group tree before the entire report and the entire group tree have been loaded.


Printing

Setting Printer Duplex and Paper Source

At runtime, you may set the printer duplex and paper source for the current report. There are two new properties that can be set and retrieved: PrinterDuplex and PaperSource. In combination with the existing properties PaperSize and PaperOrientation, you can precisely specify all aspects of the printer options.

Printer Setup Dialog

The Report Designer Component runtime has been enhanced with a new Printer Setup Dialog box. You invoke this dialog box using the new PrinterSetup method under the IReport interface.


Searching

String Search

You may now search for strings in text objects, field objects, subreports, cross-tabs and OLAP grids. You may now search field names (or object names if fields are displayed with these names instead) for strings. String searching also allows you to mark all report objects that match a string and then manipulate all these objects as a group.

Search By Formula Support

You can now search by formula in the Report Designer Component runtime. The Report Viewer will contain a boolean search button if you install the Search Expert.


Summarizing

Inserting Subtotal, Summary, Grand Total

Previously, in the RDC design time, you had to first find the database field you wanted to summarize and then right-click directly on that field before you could insert a subtotal, summary or grand total. In Version 8 you don't have to do that any more. Now you simply right-click on an empty space in the design time report and pick from a list of fields to summarize.

In addition, when you insert a subtotal for grouped data, you now havetwo options:

  • to insert a subtotal or summary field all groups, or
  • to insert a grand total field.

Note that as before, if you are creating the summary for grouped data, and in the design view you have selected an object that cannot be summarized, then the menu item Insert | Summary will be disabled. The same applies to subtotal and grand total fields.


Inserting Running Total

The RDC design time now has a shortcut for creating running total fields based on a selected database field.

You simply right click a database field and select Insert Running Total from the shortcut menu that appears. This will invoke the Create Running Total Field dialog box which automatically sets up the running total for the selected field.


Percentage Summary Fields

The Report Designer Component now supports the new Percentage Summary field. A Percentage Summary Field enables you to show a subset of data as a percentage of the entire set. For example, you can use it to show the percent contribution of each sales rep to the sales for the entire company. Previously, this had to be done using formulas.

The following changes have been made to the Report Designer Component runtime to support Percentage Summary fields:

  • the type CRSTDPercentage has been added to the enumerator type CRSummaryType,
  • the functions Add and Delete have been added to the SummaryFieldDefinitions class.


Viewer

Select Expert and Search Expert Support for the Report Viewer

The Report Viewer now supports the Select Expert and Search Expert when used in conjunction with the RDC runtime.


Web

Hyperlinks

You may now select an object in the RDC design time and create a hyperlink to a Web site or email address.

To create a hyperlink to a Web site or email address, you simply right-click an object (e.g., text, bitmap, chart) in the Designer and select Format from the shortcut menu. Go to the new Hyperlink tab in the Format Editor and set up your link.


Speed Up Loading of First Page

In the RDC runtime, you can now have the program load the first page of a report even before the total page count is calculated. You can use a placeholder for the total page count for Page N of M, and when the total page count is ready, the program will insert it back to each page.

To support this feature:

  • the PlaceHolderOptions property has been added to the IPageEngine interface. You may use this property to specify whether or not you want to delay the total page count generation.
  • The IsMissingTotalPageCount property has been added to the IPage interface. You can use this property to find out whether a page is missing the total page count.

This feature is particularly useful if you use the Report Designer Component runtime to write Web reports, where the end-user can benefit from this improvement and view the first page of a large report much sooner than before.


Web Support

You may now access the Seagate Software Web page through the Report Designer Component for online registration, support, product news, and updates. To access the web page, right-click anywhere in the Designer, and choose Help|Seagate Software on the Web.


A Closer Look at Some of the New Features

Overview:

Report Variables

Report Creation API

Using fields that bind to data sources only at runtime

Thin-client applications and meta-layer data

Field Mapping


Report Variables

The RDC now includes Report Variables. These are "smart" variables that can be used to maintain state when you code things such as running totals based on a Section Format event. These variables understand what's going on inside the report formatting process at any given time, and they enable you to do more of your report-oriented coding exclusively in VB. The discussion that follows explains why you might need to use report variables.

The RDC uses a multiple pass model to generate its reports. The number of passes the program needs to generate a given report depends on the complexity of the report. There is no "one size fits all" answer to the question, "How many passes will it take?"

During each pass, various sections in the report get fired. A Details section might get fired several times for a single record. This might happen, for example, when you have selected the "Keep Section Together" option and the program jumps back and forth between pages as it determines on which page it should print the section.

If you use a standard VB variable to calculate running totals, that variable is unable to use the built-in intelligence of the RDC. When a section is fired multiple times, the variable gets incremented each time the Format event for that section is trapped. In this case your calculations will be distorted. When you create a running total in the RDC using a Crystal Running Total field, however, the program knows to increment the field value only once for each record, regardless of how often the section is fired.

Note: The maximum allowable size for a string in a string Report Variable is 255 including the null byte. If you set a string value to more than 255, the string will be truncated.

For further discussion on "what happens when" during the report creation process, see the Report Processing Model appendix in the Crystal Reports User's Guide.


Using Report Variables

Instead of using the Dim statement to declare a Report Variable, you declare it by invoking the new AddReportVariable method when the Report Initialize event fires. This method requires you to supply a data type and variable name as parameters. For example:

Me.AddReportVariable crRVCurrency, "Total"

Note: Make certain you enclose the name of the variable in double quotes.

Once you have declared the variable, you can get its value using the GetReportVariableValue method that is part of the Report object. You can set or increment the variable using the SetReportVariableValue method. For example:

Me.SetReportVariableValue "Total", Me.Field3.Value +
Me.GetReportVariableValue("Total")

Note: Report Variables are only available in RDC runtime. If you save a report as a .RPT file to use with standalone Crystal Reports, you will lose the capability of the report variable.

For further information on Report Variables, see the Report Variables sample application in the \\SeagateSoftware\Crystal Reports\Samples\Code\Visual Basic\Report Variables folder. For a description of the sample application, see Report Variables.


Report Creation API

The RDC now includes Report Creation API methods. These methods enable you to create ad hoc reports at runtime using nothing but code. The methods can be used within Visual Basic, Microsoft Office, or in any environment from which you can access an automation server.

The RDC also provides a Report Creation Wizard object that your application can call at runtime to enable your users to create reports at runtime using an intuitive design environment. The Wizard even attempts to identify your data source so it can make the data selection automatically.

The Report Creation API methods provide the application user with Report Designer capabilities even if they are not themselves registered users of Crystal Reports. For this reason, a new licensing model is in effect for these methods only. Please refer to the license material available from the help menu in the product for further information.


Using fields that bind to data sources only at runtime

The RDC now enables you to create report templates based on unbound field objects. Then, using minimal code, you can bind field objects to a data source (or one of several data sources) at runtime. The Report Engine uses the data type and the Name property of the unbound field object to match it with a data field in the recordset.

This functionality makes it easy to build reporting into n-tier applications where you have on-demand recordsets and non-continuous data connections. It also makes it easy to build a single report that can work with a variety of recordsets, making development and maintenance more efficient.

To take advantage of this functionality:

  1. Add the RDC to your project. For further information, see Adding the RDC to your project.
  2. Choose the Unbound Fields option from the Field Explorer in the RDC.
  3. Choose a field object by data type and drag it into position where you want it to appear on your report.
  4. Set the Name property of the field object to match the name of the field in your recordset that you want it to bind to.
  5. Continue until you have all your fields in place.
  6. Write the code to activate the binding. This code example binds to a database table.

    In the code, set up an Object variable for your report. For example:

    Dim Report As New CrystalReport1

  7. Then to create the binding, code using the new Report object method AutoSetUnboundFieldSource:

    Report.AutoSetUnboundFieldSource crBMTName


Thin-client applications and meta-layer data

The discussion of unbound fields makes it look like it is extremely easy to create unbound report templates that bind to their data sources only at runtime. It is easy, but that easiness masks, somewhat, the power of this new capability. It should not be underestimated. You can use that capability to build thin-client applications that report off of meta-layer data.

If you have been interested in having your applications utilized by larger corporations, you know that you have been forced to consider a more server or multi-tiered approach. Organizations interested in keeping up with the times have been forced to move to larger customized applications for solutions like ERP systems. This combination of technology adoption has required developers, and the tools they use, to advance beyond simple applications that connect directly to a data source.

From a reporting perspective this means that you need a way to take advantage of the meta-layers within an ERP solution.


The meta-layer

A meta-layer is an intermediate data layer that holds a subset of the data in the original data source. The data in the meta layer typically has already been summarized, manipulated, and/or cleansed. Meta-layers are used when it becomes too complicated for users to understand or connect to the raw data itself.


The application and the reports

Your other challenge is based on the customizing of these systems. There is no standard database format; it is different for every company. To provide a solution, you must create client server applications that can extract the data from a meta-layer and then utilize the extracted information within the reports you provide for your users. Crystal Reports 8 takes advantage of two features to provide an answer:

  • The ability to link a report to an ADO record set.
  • The ability to create a report template using unbound fields.

Linking a report to an ADO recordset is not a new feature, but is closely associated with the new Unbound Fields capability. An unbound report field:

  • is a field type that you add to a blank report during the development of an application
  • has no data source until the user executes the report at runtime
  • acts like a placeholder on the report in situations where you don't have access to the user's data source.

This is the case, every time you write an application that is meant to connect to a customized ERP type application! Now you have a solution:

  • The final application extracts data from the meta-layer and writes it to an ADO object.
  • The RDC connects to the ADO object at runtime and populates the Unbound Field objects.

By designing your application using unbound report templates, you can still give users the ability to generate reports against this data, even though at design time the data doesn't exist.


Web-based thin-client solutions

You can also use this entire solution over the web for a true thin-client implementation You can use the same set of code (Com objects) to extract the data from the custom system and its meta-layer, and pass it to an ADO object. The CRAXDRT (using unbound fields) can then access this ADO record set and publish the report.

The main difference is that the report ends up being produced in an EPF format instead of RPT and it gets fed back to the user via the Web server in a viewer rather then in a preview window of an application.

To provide such a web solution, you would need to do your development in an ASP environment rather than a Windows-based development environment like VB, VC++ or Delphi.


Field Mapping

When you first create a report, the report draws its fields from the data source as it exists at that time. It uses the structure of the database (number of fields, field position, data type, etc.) to identify and select those fields you want placed on the report. If the structure of the database gets changed (by adding or deleting fields) after you create the report, you need to adapt the report to the new structure. The RDC now has a robust set of Field Mapping tools that you can use to accomplish this.


The FieldMapping event

In the past you have been able to use the Verify method in the Database object to verify that the structure of the data source matches that of the data source used in the report. This checks for prior changes to the structure. Now you can determine if the data source structure gets changed while you're verifying it by trapping the new FieldMapping event. The RDC fires a FieldMapping event when there is a change to the structure during the verify process.


The FieldMappingData object

The RDC also has a New FieldMappingData object that enables you to bind a report field object to a data source with a different table and/or field name, or with a different data type than that in the report. The FieldMappingData object has four read/write properties that enable you to map the changes in the data source to the database field objects in your report. These properties are FieldName, MappingToFieldIndex, TableName, and ValueType.


Integration Methods

This section is to gives you an understanding of how integrating Crystal Reports into your applications has evolved. You will also learn the benefits of using the latest technology—represented in the Report Design Component (RDC). This technology will enable you to take full advantage of the powerful Crystal Report Print Engine and create the best applications available today.

Click the appropriate link to jump to that section:

  • Overview
  • Integration methods
  • The Report Designer Component
  • The Best Tool for Your Needs


Overview

Crystal Reports is the world standard for desktop and web reporting. The Developer Edition includes many innovative features for developers who need to integrate sophisticated reporting into their Visual Basic®, Visual C++®, Visual J++®, Office, Java, Lotus Notes, and Delphi applications.

The methods developers use to integrate reporting into their applications have evolved over time. Industry leaders such as Microsoft have focused their efforts on integrating new technologies into their developer software to make it easier to create powerful applications. As companies such as Microsoft have introduced these advancements, Crystal Reports has kept pace to ensure developers can take advantage of these advancements when using our software.

Note: Visit the Seagate Software Developer Zone web site at
http://www.seagatesoftware.com/products/dev_zone.
Click Support to get links for finding documentation and knowledge base articles about integrating reporting in your applications.


Integration methods

You can choose to access the Crystal Report Print Engine and integrate Crystal Reports' functionality into your database applications in a variety of ways:

  • Report Designer Component Runtime (RDC)
  • Crystal Report Automation Server
  • Crystal ActiveX® Control (OCX)
  • Crystal Report Print Engine API
  • Crystal Visual Component Library (VCL).

When they were first introduced, each of these methods represented the latest technology available at that time. Today, you can take advantage of the full power and functionality of Crystal Reports by using the Report Designer Component, our most recent technology.

Method | Introduced in version | Project Reference Name | Description
Report Designer Component | Crystal Reports 7 | Crystal Report 8 ActiveX Designer Runtime library (craxdrt.dll) | 32-bit only COM object model, dual interface, apartment model
Crystal Reports Automation Server | Crystal Reports 6 | Crystal Report Print Engine 8 Object Library (cpeautl6.dll/cpeaut32.dll) | 32- and 16-bit COM object model, dispatch only Interface for C developers
Crystal ActiveX Control (OCX) | Crystal Reports 4.5 | ActiveX Control (crystl16.ocx/crystl32.ocx) | 32- and 16-bit OCX
Crystal Report Print Engine API | Crystal Reports 3 | Crystal Report API Interface, declares encapsulated in GLOBAL32.bas |


The Report Designer Component

The Report Designer Component (RDC) offers a dual interface COM component which is the most advanced technology available for developers. It is an ActiveX Designer that utilizes the reporting power of Crystal Reports. If you're creating applications in popular environments such as Visual Basic, Visual C++, Visual InterDev® and Office 2000 (VBA), you can use the RDC to efficiently create the most powerful reporting functionality in your applications

Although the RDC is our latest integration technology, Crystal Reports 8 supports the older integration methods (32-bit only). We recommend, however, that you begin using the newest and best reporting technology available—the RDC—to create powerful reports that support the entire range of functionality available within Crystal Reports.

To better understand why the RDC offers the best solutions, it's important to understand its architecture and how it relates to different types of developers.

The RDC consists of three main components:

  • Report Designer: for Visual Basic and Office 2000 (developer edition with VBA 6.0) developers, this component lets you create, view and modify reports directly in the Visual Basic or VBA Integrated Development Environment (IDE).
  • Automation Server: an extensive object model with hundreds of properties and methods you can use to program a report.
  • Report Viewer: used to preview reports on screen, the Report Viewer gives you great control and flexibility over the viewed report. It's a lightweight ActiveX control that contains an extensive object model. The viewer is customizable and allows you to add a custom toolbar if needed.


Visual Basic and Office 2000 (VBA) Developers

Because the report designer is an ActiveX designer, it is easy for Visual Basic and VBA developers to use:

  • The report designer is closely integrated with Visual Basic 5.0 and 6.0 and VBA 6.0, and it allows you to open, design, and customize reports directly from the Visual Basic or VBA IDE.
  • Report Experts guide you in creating the report you need, allowing you to quickly and easily design reports.
  • You can use familiar Visual Basic code to create even more advanced functionality.
  • The RDC is an easy way to give your applications powerful reporting capabilities.


Visual InterDev Developers

Many Visual InterDev developers are experienced with using Visual Basic, and are therefore familiar with integrating reports into database applications. Developers can use the same RDC automation server and Report Viewer in Visual InterDev as they use in other COM-based environments such as Visual Basic and Visual C++ to access the features of Crystal Reports. This provides one object model that offers the same control over the report engine in web applications as well as Windows applications. Developers can save time since they can build a report once and move it to either the desktop or the Web. Report Integration controls then give Visual InterDev developers an easy way to integrate reports into ASP pages.


Visual C++ Developers

If you use a development environment such as Visual C++ that supports COM, you can:

  • create reports in Crystal Reports
  • use the RDC's automation server and viewer to manipulate and preview those reports at runtime.

You will save time writing code, and can use the RDC to integrate reporting in the most logical and efficient way.


Evolution of Integration Capabilities of Crystal Reports

The integration technology available to developers has progressed in parallel with advancements in the developer market. Crystal Reports has quickly adopted the leading concepts and architecture implemented for Visual Basic, Visual C++, and other development environments. The following is an overview of how the application integration methods offered in each version of Crystal Reports have evolved over time.


Crystal Report Print Engine API

Since Version 1, Crystal Reports has exposed the Report Engine functionality via a C API that you could use to make direct Report Engine calls.

Using these direct Report Engine calls you can access more functionality than offered with the OCX. However, because it was designed for C/C++, it wasn't easy to use the API inside Visual Basic and some of the API wasn't available because of Visual Basic limitations in creating C style structures.

As a Visual Basic developer, you needed to add more code—and in many cases complex code with multiple parameters—into an application to execute a report. This was especially time consuming if you were unfamiliar with API calls.

If you have used the Report Engine API, the RDC is appealing because it offers additional functionality, and is a much easier way to experience the power of the Crystal Report Print Engine.

The Crystal Report Engine API is only available in standalone versions of Crystal Reports (i.e. version 8). No new features will be added in future releases of Crystal Reports.


The Crystal ActiveX Control (OCX)

The Crystal ActiveX Control (OCX) is one of the oldest development technologies available to developers in Crystal Reports. When OCX was first released in Crystal Reports 4.5, it was based on the latest ActiveX technology from Microsoft, thus offering state-of-the-art reporting for Visual Basic developers. Today, however, its capabilities pale in comparison to the power and flexibility available in the RDC.

  • The OCX control lacks programming depth and complete Report Engine functionality.
  • While the Crystal Report Engine provides features that are conducive to a hierarchical object model—where each report is broken down into sections with objects—this type of hierarchy isn't represented in an OCX control. At the time of its original development, the OCX revolutionized report integration because it provided developers with a graphical interface to integrate existing reports. But all of the Report Engine features can't be represented in the flat model allowed by the OCX.
  • In addition, the OCX is a wrapper around the Report Engine, which means it is less efficient and requires the distribution of more runtime components than using the RDC.

Today, the OCX supports only the smallest subsets of Report Engine functionality—the most common properties and methods. Although it's supported in newer versions, no new features have been added since Crystal Reports 6.

If you're a Visual Basic developer who has used the OCX, you will find the RDC easier to use inside the familiar Visual Basic IDE and by taking advantage of Report Creation experts.


Crystal Report Automation Server

Based on the Crystal Reports 6 Object Model, the Crystal Report Automation Server uses a hierarchical object model, unlike the "flat" model of the OCX.

  • The Automation Server provided the first object-oriented interface to the Report Engine.
  • It was also the first object model in Crystal Reports that allowed Visual
    Basic developers to access all the Report Engine features, something C/C++ developers had enjoyed since the beginning.

It was built around the Report Engine DLL. It behaved as a translation layer, taking Visual Basic code and converting it into Report Engine calls. Because of its inability to directly access the Report Engine, the Crystal Report Automation Server wasn't as efficient as it could be.

We've ensured backward compatibility in Crystal Reports 8 to allow you to leverage applications created in the previous version. However, the Crystal Report Automation Server no longer exposes all of the events and properties of the Report Engine in Crystal Reports 8. Because the Report Designer Component is COM-based, and an evolution of the Crystal Reports Automation Server, you will find it easy to migrate from the Crystal Reports Automation Server to the RDC.


Report Designer Component (RDC)

The RDC—introduced in June 1998 as a component of Crystal Reports—represents a major reengineering of the Crystal Report Print Engine. Unlike any of its predecessors, the RDC is not a wrapper; it exposes all Report Engine objects directly without any translation. The RDC is based on the same object model as the Crystal Report Automation Server. Because it is not a wrapper, the RDC is a much more efficient COM object that supports features such as dual interface, providing a more efficient way of making calls to the Report Engine.

The primary advantage of using the RDC over other developer tools within Crystal Reports is its code writing and formatting capabilities in popular development environments such as Visual Basic. The RDC provides events that enable you to manipulate the report at runtime. Within these event handlers, you can access text or field objects to modify the output of a report based on user input. Setting text in text objects or field objects, or dynamically changing pictures in picture objects, are added features unique to this interface.


The Best Tool for Your Needs

We recommend that you use the RDC to take advantage of the best functionality and features available. While we support applications created using other tools like the OCX and the Crystal Report Print Engine APIs, the RDC offers more power and is easier to use.

New features of the Crystal Report Print Engine are only available through the RDC. If you'd like to integrate them into your applications, you must change the code. Links to resources (technical briefs and tutorials) to help you migrate to the RDC are located on the Seagate Software Developer Zone web site.

Visit the Seagate Software Developers Zone at
http://www.seagatesoftware.com/products/dev_zone
to find information on the resource that best suits your needs. Chapter 9, Migrating to the RDC from the OCX of this guide shows you how to move quickly to the RDC from the OCX.

The RDC is the premium development method, and it will continue to be enhanced for developers. The latest version of the RDC is included in +Crystal Reports 8.5.


Migrating to the RDC from the OCX

This section illustrates the benefits of using the RDC for integrating reporting functionality into your Visual Basic applications. Learn how to migrate applications from the OCX to the RDC to take advantage of the latest features within Crystal Reports. Also included is an overview of the RDC, its major components, object model, and a description of its advanced features not available within the OCX.

Click the appropriate link to jump to that section:

  • Overview
  • OCX


Overview

Since it was first included in Microsoft Visual Basic, Crystal Reports has become the world standard for desktop reporting and design. It has kept pace with technological advancements by giving Visual Basic developers new ways to integrate reporting into database applications. For example, the Crystal ActiveX Control (OCX)—the tool most Visual Basic developers are familiar with—was first introduced in 1995 with Crystal Reports 4.5. In June 1998, the Report Designer Component (RDC) was launched. It's a revolutionary tool designed specifically for Visual Basic developers to create, view and modify reports within the Visual Basic Integrated Development Environment (IDE).

Note: Visit the Seagate Software Developer Zone web site at
http://www.seagatesoftware.com/products/dev_zone.
Click Support to get links for finding documentation and knowledge base articles about integrating reporting in your applications.


Summary

The RDC represents the latest in ActiveX technology and provides the following advantages over the OCX:

  • Integrates directly into the Visual Basic IDE.
  • Allows you to create, view, and modify reports using Reports Experts and familiar Visual Basic code.
  • Exposes all Print Engine features and provides the greatest number of events and objects to write code to.
  • Performs better because it is a dual interface component with no wrapper around the Print Engine.
  • Takes advantage of code completion features that are easy to use in the Visual Basic editor.
  • Is fully compatible with Microsoft Visual Basic 5.0 and 6.0.


OCX

OCX is the development interface most Visual Basic developers are familiar with because it has been a part of Crystal Reports since 1995. The OCX is based on an older version of ActiveX technology. All of its properties and methods are accessed through a single control. This limits your control of a report because it exposes only a subset of the Crystal Report Print Engine's functionality.

In addition, because the OCX acts a wrapper around the Print Engine, it's less efficient when loading a report because it can't directly access the Print Engine.

Code Comparison between the OCX and RDC

The RDC is based on the current generation of Microsoft ActiveX technology. It's the method Visual Basic developers must use to take full advantage of the features within the Crystal Report Print Engine. Applications that are created using the OCX will not be able to use the latest Crystal Reports technology. If you're planning future releases or new applications, and you'd like to use the most powerful and flexible tool, you should consider using the RDC.

You can benefit from using the RDC by getting increased control over reports, such as:

  • flexible formatting like passing text to a text object
  • enhanced printer control
  • creating report templates with unbound fields and then binding the fields to a data source (or one of several data sources) at runtime
  • report Variables that enable you to maintain state even if a report section needs to fire multiple times for a given record
  • the Create API which lets you create new objects, and even new reports, at runtime using code
  • the latest Print Engine features such as mapping and multiple parameters
  • and most importantly, the ability to create, view and modify reports inside the Visual Basic IDE.


OCX and RDC sample application comparison

OCX sample application

RDC sample application

Below are two applications which provide similar functionality—the first is created using the OCX, the second uses the RDC. The RDC example shows how to create a new application or convert an existing OCX application. With very few exceptions, you can duplicate any properties and methods set by the OCX using the RDC. Its properties and methods are very similar to the OCX, greatly reducing the time it takes you to learn the product.

The major differences between the two applications include:

  • Setting the Crystal-related Project References and Components.
  • Setting or accessing objects to get to the properties or methods needed for the report.
  • The addition of the Crystal Report Viewer for viewing reports.


Sample Application General Description

A report with a subreport is created off the xtreme.mdb database.

  • The main report contains the Customer table and a parameter field.
  • The subreport contains the Orders table and a formula field.

The OCX application consists of a Form with three Command Buttons and the OCX control.

Form Load:
  • The Report is opened.
  • The location of the database in the main report is changed.
  • The parameter in the main report is set.
  • The subreport is opened.
  • The location of the database in the subreport is changed.
  • A string is passed to the formula field in the subreport.
Command1

The report is previewed to screen.

Command2
  • The printer is selected.
  • The report is printed.
Command3
  • The export options are set to export the report to a Rich Text Format.
  • The report is exported.

A second form will be added when the application is created using the RDC. The Crystal Report Viewer is added to the second form for viewing the report.


OCX sample application

Project|References:

No Crystal References required

Project|Components:

Crystal Report Control

Form1

Private Sub Form_Load()

Open the report.

CrystalReport1.ReportFileName = App.Path & "\OCX_to_RDC.rpt"

Change the location of the database.

CrystalReport1.DataFiles(0) = App.Path & "\xtreme.mdb"

Pass the parameter value to the main report.

CrystalReport1.ParameterFields(0) = "Param1;Main Report Param;True"

Pass the selection formula to the main report.

CrystalReport1.ReplaceSelectionFormula _
"{Customer.Last Year's Sales} < 50000.00"

Open the subreport.

CrystalReport1.SubreportToChange = "Sub1"

Change the location of the database in the subreport.

CrystalReport1.DataFiles(0) = App.Path & "\xtreme.mdb"

Pass the formula to the subreport.

CrystalReport1.Formulas(0) = "Formula1= " & "'Subreport Formula'"

Set CrystalReport1 back to using the main report.

CrystalReport1.SubreportToChange = ""
End Sub
Private Sub Command1_Click()

Set the destination to window.

CrystalReport1.Destination = crptToWindow

Preview the Report.

CrystalReport1.Action = 1
End Sub
Private Sub Command2_Click()

Set the printer driver.

CrystalReport1.PrinterDriver = "HPPCL5MS.DRV"

Set the printer port.

CrystalReport1.PrinterName = "HP LaserJet 4m Plus"

Set the printer name.

CrystalReport1.PrinterPort = "\\Vanprt\v1-1mpls-ts"

Set the destination to printer.

CrystalReport1.Destination = crptToPrinter

Print the report.

CrystalReport1.Action = 1
End Sub
Private Sub Command3_Click()

Set the Report to be exported to Rich Text Format.

CrystalReport1.PrintFileType = crptRTF

Set the Destination to Disk.

CrystalReport1.Destination = crptToFile

Set the path and name of the exported document.

CrystalReport1.PrintFileName = App.Path & "\OCXExport.rtf"

Export the report.

CrystalReport1.Action = 1
End Sub


RDC sample application

To migrate this application to the RDC, remove the OCX component from Form1, and remove the Crystal Report Control from the Project|Components menu, in addition to the steps below:

Project|References

Reference the Crystal Report 8 ActiveX Designer Runtime Library

Project|Components

Crystal Report Viewer Control

Add a second form

Add the Crystal Report Viewer Control to Form2

The properties and methods are accessed from individual objects. Following this code sample is a detailed description on the RDC Automation Servers Object Model.

The RDC will open a standard Crystal Report (.RPT). The Report could have been Imported into or recreated in the RDC ActiveX Designer (.DSR).

Form1:

Declare the application object used to open the rpt file.

Dim crxApplication As New CRAXDRT.Application

Declare the report object.

Public Report As CRAXDRT.Report

Private Sub Form_Load()

Declare a DatabaseTable object for setting the location of the database. This object will be used for the main and subreport.

Dim crxDatabaseTable As CRAXDRT.DatabaseTable

Declare a ParameterFieldDefinition object for passing parameters.

Dim crxParameterField As CRAXDRT.ParameterFieldDefinition

Declare a Report object to set to the subeport.

Dim crxSubreport As CRAXDRT.Report

Declare a FormulaFieldDefinition object for passing formulas.

Dim crxFormulaField As CRAXDRT.FormulaFieldDefinition

Open the report.

Set Report = crxApplication.OpenReport _

(App.Path & "\OCX_to_RDC.rpt", 1)

Use a For Each loop to change the location of each DatabaseTable in the Reports DatabaseTable Collection.

For Each crxDatabaseTable In Report.Database.Tables

crxDatabaseTable.Location = App.Path & "\xtreme.mdb"

Next crxDatabaseTable

Set crxParameterField to the first parameter in the parameterfields collection of the main report.

Set crxParameterField = Report.ParameterFields.Item(1)

Pass the value to the main report.

crxParameterField.AddCurrentValue "Main Report Parameter"

Set crxSubreport to the subreport 'Sub1' of the main report. The subreport name needs to be known to use this method.

Set crxSubreport = Report.OpenSubreport("Sub1")

Use a For Each loop to change the location of each DatabaseTable in the Subreport Database Table Collection.

For Each crxDatabaseTable In
crxSubreport.Database.Tables

crxDatabaseTable.Location = App.Path &
"\xtreme.mdb"

Next crxDatabaseTable

Set crxFormulaField to the first formula in the formulafields collection of the subreport.

Set crxFormulaField = crxSubreport.FormulaFields.Item(1)

Pass the formula to the subreport.

crxFormulaField.Text = "'Subreport Formula'"

End Sub

Private Sub Command1_Click()

Call Form2 to preview the Report.

Form2.Show

End Sub

Private Sub Command2_Click()

Select the printer for the report passing the Printer Driver, Printer Name and Printer Port.

Report.SelectPrinter "HPPCL5MS.DRV", "HP LaserJet 4m Plus", "\\Vanprt\v1-1mpls-ts"

Print the Report without prompting the user.

Report.PrintOut False

End Sub

Private Sub Command3_Click()

Declare an ExportOptions Object.

Dim crxExportOptions As CRAXDRT.ExportOptions

Set crxExportOptions to the Report object's ExportOptions.

Set crxExportOptions = Report.ExportOptions

Set the report to be exported to Rich Text Format.

crxExportOptions.FormatType = crEFTRichText

Set the destination type to disk.

crxExportOptions.DestinationType = crEDTDiskFile

Set the path and name of the exported document.

crxExportOptions.DiskFileName = App.Path & "\RDCExport.rtf"

Export the report without prompting the user.

Report.Export False

End Sub

Form2:

Private Sub Form_Load()

Set the Report source for the Crystal Report Viewer to the Report.

CRViewer1.ReportSource = Form1.Report

'View the Report

CRViewer1.ViewReport

End Sub

Private Sub Form_Resize()

This code resizes the Report Viewer control to Form2's dimensions.

CRViewer1.Top = 0

CRViewer1.Left = 0

CRViewer1.Height = ScaleHeight

CRViewer1.Width = ScaleWidth

End Sub


Introducing the Report Designer Component

This section introduces the Report Designer Component (RDC) and explains it's architecture along with some possible development scenarios. It also provides additional sources for help and information on the RDC, including sample applications that present the RDC in real-world scenarios.

Click the appropriate link to jump to that section:

  • The Report Designer Component
  • How to Get Additional Information
  • Sample Reports
  • Sample Applications
  • Report Wizard
  • Complex Applications


The Report Designer Component

The Report Designer Component (RDC) is a powerful solution for Visual Basic developers who quickly and easily integrate reporting into their database applications. It's an ActiveX designer object that packs the reporting power of Crystal Reports into a lightweight add-in for Visual Basic 5.0 or 6.0. You can open, design and customize reports within the Visual Basic IDE. In addition:

  • Intuitive Report Experts make it flexible and efficient to connect to data and integrate powerful reports into applications.
  • With hundreds of report properties, methods and events, you have complete control over your report designs, using familiar Visual Basic code.
  • Report distribution is simplified through a small component count and free runtime.
  • Reports can be packaged within the applications' executable or stored outside the application in the traditional (.rpt) format.

Note: Get the latest news about the Report Designer Component from the Seagate Software Developer Zone web site at
http://www.seagatesoftware.com/products/dev_zone


Design time

At design time, the Report Designer Component provides a user interface that closely integrates with the Visual Basic IDE. Through the user interface, you design and manipulate reports and report data. This interface includes events that can be directly programmed from within Visual Basic.

The Report Designer Component uses the Active Data Driver for connecting to ISAM, ODBC, and SQL databases through Data Access Objects (DAO), Remote Data Objects (RDO), ActiveX Data Objects (ADO), and Data Environments (Visual Basic 6.0 only). You can design the data set from within Visual Basic, then apply it to the report contained by the Report Designer Component.

When working in Visual Basic, you will often need to use the Report Viewer for ActiveX as a user interface to display reports. The Report Viewer is an ActiveX control that you can drop to a standard Visual Basic Form. The Report Viewer is where your report is displayed at runtime.


Runtime

The user interface provided by the Report Designer Component at design time does not appear in your application at runtime, or when it is compiled into an executable file. Instead, the Report Designer Component is accessed directly by your Visual Basic code. New for version 8.5 is the Embeddable Crystal Reports Designer Control. This allows you to provide your users with the ability to design or edit Crystal Reports within your application using the same interface as the design time control. However reports can be opened and saved only in the Crystal Report format (.rpt) and not in the ActiveX Designer format (.dsr) of the design time control.

The Report Designer object model provides a complete object hierarchy for direct manipulation in Visual Basic. The object model can be accessed through both the RDC runtime engine and the RDC design and runtime engine. See CR Automation Server for more information.

The Active Data Driver is also available at runtime, through the Report object of the Report Designer Component object model, and can be assigned a new set of data based on user interaction with your application. You design a Recordset or Resultset object in Visual Basic using the DAO, RDO, or ADO object model, and pass it to the report.

Finally, the Report Viewer takes center stage at runtime, connecting to the Report Designer Component and displaying the embedded report. With careful design and placement on the Form, the Report Viewer appears as a window inside your application.


RDC Architecture

If you aren't familiar with the RDC, you should note that it consists of five components. Together, these components enable you to create, design, edit, program, and preview, print, or export your reports:


Report Designer

The Report Designer is integrated tightly within the Visual Basic 5.0 and 6.0 IDE, enabling you to create, view, and modify reports without leaving Visual Basic. This component was specifically created for Visual Basic developers.


Automation Server

There are two automation servers provided with the RDC. The Crystal Reports ActiveX Designer Runtime Library (craxdrt.dll)—known as the RDC runtime engine, and the Crystal Reports ActiveX Designer Design and Runtime Library (craxddrt.dll)—known as the RDC design and runtime engine. Both offer the same extensive object model with hundreds of properties and methods for you to use to manipulate the report at runtime. See Unification of the RDC object model for more information on when to use each automation server.


Crystal Report Viewer

The Crystal Report Viewer is an ActiveX control that you can use to preview reports on screen. The viewer is loaded with customization options to give you great control over your interface and over the viewed report itself.


Embeddable Crystal Reports Designer Control

The Embeddable Crystal Reports Designer Control (Embeddable Designer) is an ActiveX control that you can use to allow your users to design and edit Crystal Reports in your application at runtime.

Component Description

Crystal Report Designer UI Component (craxdui.dll)

A COM (Component Object Model) component that provides the user interface at design time for the user to interact with and create or modify the report.

Crystal Report Designer Design and Runtime Time Component (craxddrt.dll)

An underlying COM component that provides services for the user interface component. The component also encapsulates all of the report objects and is responsible for all of the data processing and report layout. Use this component with client based applications that incorporate the Embeddable Designer.

Crystal Report Designer Run Time Component (craxdrt.dll)

The component that encapsulates all of the report objects and is responsible for all of the data processing and report layout. Use this component with any Client based or server side application that does not incorporate the Embeddable Designer.

Active Data Driver (p2smon.dll)

A data access driver that provides access to various types of object data sources including DAO, RDO, and ADO.

Crystal Report Viewer for ActiveX (crviewer.dll)

An Active X control which can be drawn on a form and manipulated at design time. It provides a rich object model used to modify user interaction with the report at runtime. This component is required only if a developer wants to provide on-screen display of reports at runtime.

VB Form

The Crystal Reports Report Viewer Control must be embedded on a Visual Basic Form in order to display the report on screen. The Create Report Expert can automatically add a Form with the Report Viewer embedded to the project when you finish designing a report with the Expert.

Data Set

One of the following:

  • Data Access Object (DAO) Recordset
  • Remote Data Object (RDO) Resultset
  • Active Data Object (ADO) Recordset
  • VB Data Environment
  • Crystal Data Object (CDO)
  • Crystal Data Source Type Library object
  • ODBC Direct

These objects do not need to be valid at design time. For example, you could construct a report template at design time without the data being available. This is handled through Data Definition Files. However, the data set objects must be present and valid at runtime to generate a report.


Combinations of RDC Components

The three RDC components can be used together or individually, in any combination. The following table identifies which of the components you need to use in your project:

Using the Report Designer with the Automation Server

  • VB and VBA only
  • for designing reports within IDE and manipulating the reports with code
  • not necessary to preview the reports
  • reports can be printed or exported
  • use the Crystal Formula Language, VB or VBA code for expressions in the report.

Using all three RDC components

  • VB and VBA only
  • want to design reports within IDE and manipulate the reports with code
  • reports can be previewed, printed or exported
  • use the Crystal Formula Language, VB or VBA code for expression in the report.

Using the Automation Server and the Crystal Report Viewer

  • VB and VBA, C++, Visual InterDev, Visual J++
  • want to design reports using Crystal Reports, preview from application, and manipulate the reports with code
  • reports can be printed or exported
  • use the Crystal Formula Language, VB or VBA code for expressions in the report.

Using the Automation Server, Embeddable Designer, and the Crystal Report Viewer

  • VB and VC++
  • want to allow your users to design or edit their own Crystal Reports
  • reports can be saved, printed, exported and previewed.
  • use the Crystal Formula Language, VB or VBA code for expressions in the report.

Using the Automation Server by itself.

  • VB and VBA, C++, Visual InterDev, Visual J++
  • want to design reports using Crystal Reports and manipulate the reports with code
  • reports can be printed or exported
  • use the Crystal Formula Language, VB or VBA code for expressions in the report.


Adding the RDC to your project

The installation program will attempt to add the menu item Add Crystal Reports 8.5 to the Project menu of the VB IDE when you install the RDC. If that menu item appears, you simply select it to add the RDC to your project.

If the menu item does not appear on the Project menu, you will first need to add it manually, and then you can add the RDC to your project.

To add the RDC to your project
  1. Choose Components from the Project menu.
  2. Click the Designers tab in the Components dialog box when it appears.
  3. Select Crystal Reports 8.5 on the Designers tab. This will add the menu item to the Project menu.
  4. Finally, select Add Crystal Reports 8.5 from the Project menu.

The RDC is now ready to use within the VB IDE.


How to Get Additional Information

Seagate Software supplies an extensive set of tools to help you master the RDC quickly and easily. These include:

Crystal Reports User's Guide

The Seagate Software Web Site

Object Browser

Properties Window

Sample Reports

Sample Applications


Crystal Reports User's Guide

Since the capabilities of the RDC mirror the capabilities of Crystal Reports, you can use the Crystal Reports User's Guide to learn about the RDC's powerful reporting capabilities. For example, if you want to learn the details of the Select expert, how to link a subreport to its parent report, or just more general information on report creation, you should refer to the User's Guide. This documentation is available in printed form as well as a searchable electronic (PDF) form on the CD. You can find the User's Guide (Usergde.pdf) in the Docsfolder on the CD.


The Seagate Software Web Site

Seagate Software provides a wide range of developer support information and tools on its web site at
http://www.seagatesoftware.com/products/dev_zone

The web site offers these support tools and more:

  • downloadable files and product updates
  • developer samples
  • a comprehensive knowledge base showing solutions and workarounds to a wide range of technical problems
  • technical briefs, detailed documents that discuss complex issues and/or explain how to use various sophisticated product features
  • FAQs: quick answers to your most common questions
  • Release Notes: details about known issues, product features, enhancements, and fixes.

The web site is updated continually so you will always be able to find current information to help you with your development challenges.


Object Browser

A source of support for many VB programmers is the VB Object Browser. Use the Object Browser to navigate the RDC automation server object model (CRAXDRT), the Report Viewer object model (CRVIEWERLibCtl), the various objects used in your project (Project n), and the VB and data object models. The Object Browser introduces you to the hierarchy of the object models, and provides you with useful information about the various classes and members in the object models.


Properties Window

The RDC exposes each object in an RDC report. This means you can view all of the design time properties and options in the Properties Window of the VB IDE. Simply select an object in the report and you can see and set its various properties visually.


Sample Reports

The program includes many sample reports you can use to learn sophisticated reporting techniques. With a full installation, you can find these samples in the \Crystal Reports\Samples\Reports folder.


Sample Applications

Crystal Reports contains over 18 Visual Basic sample applications. These applications show you how to use the RDC in real-world situations.

With a complete installation, you will find the sample applications in the \\Seagate Software\Crystal Reports\Samples\En\Code\Visual Basic folder. There are samples for C++ and the Web in the \Code folder. The sample applications provide you with one of the most direct and tested methods for learning the RDC.

The applications contain usable code that can be modified and plugged into your own programs. They also present great ideas for using the RDC. By studying these ideas, you may be able to generate new business by offering clients sophisticated capabilities.


Visual Basic Samples

The following sample applications have been created for Visual Basic developers:

Simple Application

ADO Connection Methods

Change Runtime Location of OLE Object

Employee Profiles

Inventory Demo

Load Picture Demo

Microsoft Office Samples

No Data in Report Event

Printer Settings

Report Object Creation API

Report Variables

Report Wizard

Search and Select Experts

Simple Demo

Unbound fields

Viewer

Viewer Runtime options

Complex Applications


Simple Application

Most of the sample applications focus on solving a single problem or a small set of related problems. If you're a first time user of the RDC, you'll find the application called Simple Demo a good place to start.


ADO Connection Methods

This application demonstrates the two new methods to add ADO data sources to a report:

  • AddADOCommand takes an active ADO connection and ADO command object as parameters. In this example, a new connection is created to a database, and the resulting recordset is assigned at runtime to the report.
  • AddOLEDBSource takes as parameters the name of an active ADO connection and the name of a table that can be accessed through that connection. In this example, the connection setup through the VB Data Environment is used as a data source.

Both methods can be used with either the VB Data Environment or another data source created at runtime.

Note: Notice in the Designer that there is no data source attached to the report at design time.


Change Runtime Location of OLE Object

This application demonstrates how you can set the location of an OLE object at Runtime using the SetOleLocation command.

This application takes three different OLE objects:

  • a bitmap
  • part of an Excel spreadsheet
  • part of a Word document.

This application cycles through them so a different object gets printed each time the Details section gets formatted.


Embeddable Designer Control

This application demonstrates how to include the Embeddable Crystal Reports Designer Control in an applicaion. It shows how to add a new or existing report to the Embeddable Designer, how to display the report in the Crystal Report Viewer, and how to refresh the report in the Crystal Report Viewer so it displays any changes made in the Embeddable Designer.


Employee Profiles

This application demonstrates how you can set and format the text in report text objects at runtime.


Inventory Demo

The Inventory Demo is a sample application that displays a report. It shows you how to use the Report Initialize section for report level manipulation. It also includes how to change the BackColor of the report Details section conditionally for those items that need to be ordered.


Load Picture Demo

The Load Picture application shows you how to load a picture into the report at runtime. It also shows you how to change some of the values and properties of some of the text objects in the Details section of the report at runtime.

The program also shows you ways to implement calculations and calculated fields in the RDC. The two methods are:

  • using the Crystal Formula Language
  • using VB code in the Section_Format event procedure.

This example describes how to perform calculations in the Section_Format event using VB.


Microsoft Office Samples

Visit the Seagate Software Developer Zone web site at
http://www.seagatesoftware.com/products/dev_zone

To search for Microsoft Office sample applications click Support, and then click the Download Files and Updates link.


No Data in Report Event

This application demonstrates the new NoDataInReport event.

The "No Data" event is triggered when the data set in the report is empty. In this sample, the code applies a filter to the data that causes the report to have no data. It then traps the NoDataInReport event and displays a message box that allows the user the option to view the report without any data or just to view a blank page.


Printer Settings

This application demonstrates how to change the report printer settings at runtime using code.

  • There are four new report properties that allow you to easily retrieve and set PaperSize, PaperOrientation, PaperSource, and PrinterDuplex for the report printer options. All of these are demonstrated.
  • There is also a new method called PrinterSetup that provides a Windows standard printer setup window to allow the user to change the printer properties directly at runtime. This is demonstrated as well.

The two methods are independent of each other. For example, changing the Windows standard printer setup will not alter the report printer settings and vice-versa. These new properties and the new method give you much more control over how the report is printed.


Report Object Creation API

This application demonstrates the use of the new Report Object Creation API.

The Creation API functions allow runtime creation of report objects, including text, database field, unbound field, chart, special, box, cross-tab, BLOB field, line, picture, summary, and subreport objects.

  • You can add these report objects at runtime to an existing report that you created in the RDC.
  • You can also create a blank report at runtime and add these objects to that blank report. This sample demonstrates the second method.

All properties that are normally available for each object at runtime are also available for the objects you create.

This sample shows you how to create text, database field, unbound field, summary, picture box and line objects. For information about more advanced uses of the Creation API, please see the Pro Athlete Salaries sample application.


Report Variables

This application demonstrates the use of the new Report Variable capability.

The RDC now includes Report Variables. These are "smart" variables that can be used to maintain state when you are coding items such as running totals based on a Section_Format event. These Crystal variables can be used in your VB code. They understand what's going on inside the report formatting process at any given time, and they enable you to do more of your report-oriented coding exclusively in VB.

This sample describes how to use Report Variables to calculate totals based on only part of the data. Since Report Variables accept any valid value from the VB environment, you can use values that only exist at Runtime to change the formatting of your report.

In this sample, there are three columns based on a database: one column of currency values, one column of integer values, and one column of non-integer values.

  • The first column changes to a blue color when the sum of the values in the column is greater than a random value. A total is displayed in the lower part of frmMain showing the total of the values colored blue.
  • Records in the second and third columns change color when the sum is greater than a different random value. The sum is then reset. This can be useful if you wish to start and restart a totalling operation in the middle of a report.
  • A String Report Variable is used to build a string consisting of the first digit of each green highlighted value. You could use this method to easily extract individual string values from a report field.

Note: Report Variables can only be set and retrieved while the report is formatting.


Report Wizard

You can use the Report Wizard with the Report Creation API to enable users to create entirely new reports at runtime and then view or save the report. When you implement the Wizard, you save yourself the necessity of writing "create" code for each of the objects your users put into their new report. This application shows you how easily you can implement the Wizard in your code.

You can also use the Report Wizard as a starting point for creating a custom report wizard that allows you to set your own defaults for report creation.


Search and Select Experts

This application shows you how to control the Search and Select Wizards in the Report Viewer using code.

The Search and Select Wizards allow advanced filtering and highlighting of data displayed in the ActiveX viewer. In this sample, two different methods of using the Search and Select Wizards are demonstrated:

  • Two command buttons on the main form display a search or select wizard with predefined fields and ranges already set for the user. The only displayed fields and ranges are those that have been added at runtime.
  • The Search and Select Expert buttons on the top right part of the viewer are over-ridden, allowing you to specify default criteria to search for. Alternatively, the default search and select experts can also be displayed.


Simple Demo

This simple demonstration presents an introduction to the Report Designer. Many of the basic methods used in manipulating and creating reports are discussed in the code comments. This is a good starting point if you are unfamiliar with the RDC.


Unbound fields

This application shows you how to create a report template using the new Unbound Fields capability. It also shows you how to bind the fields at runtime to a data source that you also create at runtime.

In this sample, there are five unbound fields created in the report. Notice that there is no data source added to the report at design time at all—the data source is created and added to the report at runtime.

You can also use Unbound fields in formulas, although this sample does not demonstrate this use.

Unbound fields give you great flexibility in your programming. They even allow you to create a single report template that can be bound to a variety of data sources at runtime in response to user input. This enables you to create a wide range of custom reports all from a single template. See the Pro Athlete Salaries application for a demonstration of this capability.


Viewer

This simple application shows you how you can create your own Report Viewer toolbar and manipulate the ActiveX viewer using your own custom buttons.


Viewer Runtime options

This application demonstrates the many ways you can manipulate the Report Viewer at runtime. It also shows you how to implement the use of the Select Expert and the Search Expert in the Viewer.

All of the check boxes on the main form correspond to viewer properties that you can change at runtime. In this sample, there are more than 21 viewer properties that are manipulated. Note that to enable the Select Expert and Search Expert, you must reference the Crystal Select Expert OLE control module and you must place the Select Expert Control on the form.

The Select/Search Expert is essentially invisible on the form and is located immediately to the left of the About Sample Command Button in this sample.


Complex Applications

The following three applications are large and complex. They each demonstrate many of the RDC capabilities.


Xtreme Mountain Bikes

This application was included with Version 7. It has been updated in this version to showcase many of the new RDC capabilities.


Pro Athlete Salaries

This application shows a very sophisticated use of the Create Report API, Unbound Fields, and a previously-undocumented method for using the Tables.Add method. This report is worth studying because it demonstrates the powerful things you can do with the RDC through code alone.

Note: The Designer does not appear in the Project Explorer. This is because the report is actually a template report created at runtime using Unbound Fields and the Create API, and the fields are bound at runtime to a custom recordset generated at runtime based on user input.


First Class Hotels

The sample demonstrates a number of Crystal Reports features that are new to version 8, as well as possible advanced uses for some existing features.

The main form in the sample, frmMain, is used for managing the reservations. Some features include:

  • The report displayed in the window is automatically updated whenever a reservation is added, the customer name changed, or the date range changed.
  • Double-clicking on a customer name or room number in the report will bring up a form containing information about that customer or room.
  • Clicking on one of the two miniature notepad icons in this window will also cause this same information report to be displayed.
  • The billing report that can be displayed by double-clicking the report, or clicking the notepad icons, only displays information between the start and end dates shown at the bottom of the reservation form.

The Room form, frmRoom, contains these features:

  • Allows adding/removing of hotel room numbers.
  • Clicking on the miniature notepad icon in this window will cause the information report to be displayed. The information will be displayed for all dates that the room has been used and is not restricted by a start or end date.

The Price form, frmPrice, contains these features:

  • Allows adding/removing of hotel room prices.
  • Customer: Allows adding/editing/removing of customers.
  • Clicking on the miniature notepad icon in this window will cause the information report to be displayed. The information will be displayed for all dates that the customer has stayed at the hotel and is not restricted by a start or end date.

This application uses many of the methods from earlier releases as well as this release. Here is a list to help you determine if this application has the answers you're looking for (* denotes new in version 8):


Crystal Reports Viewer Object

Methods: | Properties: | Events:
PrintOut | EventInfo.Text | DblClicked
Refresh | EventInfo.Type |
ReportSource |  |
ViewReport |  |


Crystal Reports Report Object

Methods: | Properties: | Events:
*AddReportVariable | Get and Set PaperSize | *BeforeFormatPage
*GetReportVariable | Get and Set PaperOrientation | *EndFormatPage
*SetReportVariable | *Get and Set PrinterDuplex | Initialize
RecordSelectionFormula | *Get and Set Papersource | *NoData
*SetUnboundFieldSource | Database.Tables().Location | Section_Format
 | LeftMargin |
 | RightMargin |


Quick Start for using the RDC

This section helps you get started using the Report Designer Component (RDC) in Microsoft Visual Basic. Three examples provide you with the basic skills needed to use the RDC. You will find a high-level explanation of the steps required to add the RDC to a project, a tutorial on adding an existing report to the RDC, and a tutorial on creating and modifying a new report.

Click the appropriate link to jump to that section:

  • Overview
  • Bullet Point Quick Start
  • Open an existing report
  • Create and modify a report


Overview

Using the RDC will add powerful reporting capabilities to your application, and you can do it all from the Visual Basic IDE.

Note: For information on using the RDC with other development environments, See Chapter 10, Working with Visual C++ and Visual InterDev.

The following three sections were designed to get you started with the RDC:

Bullet Point Quick Start.
If you only need minimal instructions for using the RDC, this section is for you. It includes a higher level, bulleted explanation about how to create, view, and manipulate a report through the RDC.

Open an existing report.
If you have created a report in the standalone version of Crystal Reports and you want to open it through the RDC and preview it in the Report Viewer, you will find this section useful. It includes a lower level, step-by-step approach.

Create and modify a report.
If you want to create, preview, and manipulate a report through the RDC, you will find this section extremely useful. This is also a lower-level, step-by-step approach. It mirrors the procedure of the Bullet Point Quick Start but describes each of the bullet points in more detail.

If you have questions that are not answered by these samples, please see the Sample Applications at \Crystal Reports\Samples\Code.


Bullet Point Quick Start

To add reporting capabilities to your application using the RDC:

  • Add the RDC to your project
      • With a complete install, the option Add Crystal Reports 8 appears on the Project menu in the VB IDE. Select Add Crystal Reports 8.
      • If the option does not appear, select Components from the Project menu and check the Crystal Reports 8 option on the Designers tab. Then select Add Crystal Reports 8 when it appears on the Project menu.
  • Select a data source

    When you add the RDC to your project, the program presents the Crystal Report Gallery dialog box. If you're not familiar with Crystal Reports, choose the Using Report Expert option and choose Project data from the Data tab in the Standard Report Expert when it appears. This enables you to select the newest technology, the Active Data recordsets for building your report. Select one of the ODBC(ADO) data sources from the combo box, add a new data source, or supply a connection string for an ADO OLE DB connection.

  • Create a report

    From the Standard Report Expert, you can build your report by adding fields, setting up grouping and totalling, specifying your sort options, adding charts and selection criteria if you wish, and even adding a professionally designed look. You can do that by using the various Expert tabs.

  • Add the Report Viewer to your project

    When you select Finish in the Standard Report Expert, the program automatically adds a form to your project and installs the Report Viewer on the form. It also writes the necessary code for displaying your report in the viewer and resizing the viewer whenever the form is resized.

      • If you don't want the Viewer installed automatically, or if you don't want the Viewer form to be your start-up form, you can change those actions in the Default Settings dialog box.
      • You get to the Dialogue by right-clicking in the RDC and selecting Designer and then Default Settings from the shortcut menu when it appears.
  • Create a UI for users to modify the report at runtime

Now that you have a report, you may want to manipulate it with code based on user input. If you haven't done so already, here is the point where you could build the UI for the user using Visual Basic.

  • Write the code that does the modifications

    Now you can write the code that ties the users UI selections to the report.

      • Each object in the report is exposed in the Properties window of the VB IDE.
      • Double-click any object and you can write code for the object.
      • Double-click on a section of the report and you can write code that affects the section and the objects in the section.
      • By referencing an object name in your UI code or the object index through one of the many Collections, you can manipulate that object directly based on user input.
  • Preview, print, or export the report.

    When you have completed the above, you can run the application and preview, print, or export the report using the UI controls you've set up to do it.

Now you have integrated the most powerful reporting tool into your application.


Open an existing report

In this example, you will open an existing report file in Visual Basic. This will demonstrate how to import existing reports (*.RPT files) and enable you to become familiar with the Report Designer Component user interface. This tutorial uses Crystal Reports 8.5 and Microsoft Visual Basic 6.0.

Ensure that you have completed the installation of the Report Designer Component files and make note of the installation directory if you did not accept the default selection.

To open a report directly within Visual Basic 6.0
  1. Open Visual Basic and create a new Standard EXE project by selecting Standard EXE from the start up dialog or selecting it from New Project under the File menu.
  2. Add the Report Designer Component to Visual Basic if not already added during the installation process.
  3. From the Project menu, select Components.
  4. Click the Designers tab and check Crystal Reports 8. Click Apply and then click Close. The Report Designer is now available in this project and any projects you create in the future.
  5. Now we need to insert the Report Designer into the project form. On the Project menu, point to More ActiveX Designers and then click Add Crystal Reports 8.
  6. The Crystal Report Gallery appears displaying the different types of Report Experts that are available. Since you will be opening an existing report file, click From an Existing Report. Click OK.
  7. Browse to the report called World Sales Report at \Crystal Reports\Sample\Reports\General Business\. Click Open. Depending on your setup, you may be presented with a dialog that asks you about adding a form at runtime. Click OK.
  8. The Report Designer Component is added to your project and the report layout is displayed in the design window. Report files created in any version of Crystal Reports can be imported in this manner. Before you run the report, right-click on Form2, and select View Code. You should see Visual Basic code that looks like this:

Dim Report As New CrystalReport1

Private Sub Form_Load()

Screen.MousePointer = vbHourglass

CRViewer1.ReportSource = Report

CRViewer1.ViewReport

Screen.MousePointer = vbDefault

End Sub

Private Sub Form_Resize()

CRViewer1.Top = 0

CRViewer1.Left = 0

CRViewer1.Height = ScaleHeight

CRViewer1.Width = ScaleWidth

End Sub

This default code, inserted by the Report Designer Component, will point the runtime Crystal Report Viewer at the report to display the results. This makes it easy to flip between the report design window and the finished report. You can add to or modify this code, but for now we'll just view the report.

  9. From the Run menu select Start (F5) or click on the Start button on the Visual Basic toolbar. After a few seconds, you will see a form displaying the finished report in the Crystal Report Viewer. You can resize the form by dragging the lower right hand corner of the Viewer. You can save this project if you like, but it will not be required to complete the steps in the next section.

Now that you have opened and viewed a report, feel free to go back and explore some of the right-click and property settings in the Report Designer window. You may also want to browse the CRViewer class of the CRVIEWERLibCtl object to see some of the properties and methods that you can use to customize the appearance of the viewer at runtime.


Create and modify a report

In this example, we'll create and modify a simple report using the Report Designer Component. This will guide you through the basic steps in connecting to a data source and creating a report. The report you will be creating is a Sales by Region report based on a Microsoft Access database. We'll use the Report Experts to help create the report quickly and easily, then we'll modify some of its properties and make it more interactive by adding some event-driven code.

This exercise only touches on a few of the hundreds of properties and methods available but will give you an idea of how simple it is to fully integrate and customize reports in your Visual Basic projects.

To Add the RDC to your project
  1. Open Visual Basic and create a new Standard EXE project by selecting Standard EXE from the start up dialog or selecting it from New Project under the File menu.
  2. Add the Report Designer Component to Visual Basic if not already added during the installation process.
  3. From the Project menu, select Components.
  4. Click the Designers tab and check Crystal Reports 8. Click Apply and then click Close. The Report Designer is now available in this project and any projects you create in the future.
  5. Now we need to insert the Report Designer into the project form. On the Project menu, point to More ActiveX Designers and then click Add Crystal Reports 8.5. (In some environments, Add Crystal Reports 8.5 will appear as an option itself on the Project menu.)
To select a data source
  1. Check Using Report Expert and select Standard. Click OK. The Standard Report Expert appears. This window allows you to select from either Project or Other data sources. Typically, you use a project-based data source. The Other option enables you to use the native data drivers included with Crystal Reports.
  2. We'll connect to the ODBC data source using ADO. Click the Project button.
  3. The Select Data Source window appears with ODBC selected by default. Select Xtreme Sample Database from the list of data sources. To see which options are available, click Advanced. The Advanced Options dialog appears. Click OK to accept the default of connecting using ADO.
  4. Now that you've specified the data source and connection method, you need to specify which tables to use. Click Next in the Select Data Dialog. This brings up the Select Recordset dialog.
  5. Select Customer from the object list and click OK to return to the Data Tab. The item ado should be displayed in the Tables list box.
To create a report
  1. Now that you've selected the database and the table, you need to specify the fields to include in the report. Click Next to move to the Fields tab.
  2. Select the Customer Name database field from the Available Fields list, then Click Add to add the field into the Fields to Display box. Do the same for the Last Year's Sales, City and Region fields.
  3. Click on the Group tab and select the Region field, then click Add to add the field into the Group By box. Do the same for the City field. This will group your data by Region and, within each region, by City. By default, the Sort Order for the Region and City Fields is in Ascending Order.
  4. Click the Total tab. Because Last Year's Sales is the only numeric field in the report, the Report Expert automatically selects it for totaling.
  5. Click the Top N tab. For the Region Tab, choose Sort All Groups based on Sum of Last Year's Sales. Do the same for the City tab.
  6. Click the Chart tab and click the Pie in the Chart Type list on the Chart|Type tab. Select the pie chart with 3D visual effect.
  7. Click the Chart|Data tab. The Report Expert automatically selects to create the chart based on the sum of Last Year's Sales.
  8. Click the Chart|Text tab. In the Title box, type "Sales by Region".
  9. Finally, to give the report a professional look, go to the Style tab in the main set of Expert tabs and select the Executive, Trailing Break style. Click Finish. The RDC creates your report.
To add the Report Viewer to your project
  1. The Report Expert presents you with the option of adding a form with the Crystal Report Viewer control and setting this as the start-up object. Click OK to accept the defaults. The Expert will format the report and display it in the design window.
  2. Click the Start button on the Visual Basic toolbar or press F5 to run your project. After a few seconds, you will see a form displaying the finished report in the Crystal Report Viewer.

This exercise has shown the basic steps for creating a new report. Although you don't always have to use the Report Experts, they make connecting to your data source and creating the initial report fast and easy. You can then alter the look and feel of the report using the Report Designer window. Common tasks like field formatting, adding text and modifying field positions can be accomplished by dragging fields or altering their properties. These can be set using Visual Basic code or in the Visual Basic object properties window.


Create a UI for users to modify the report at runtime

When you add report capabilities to your application, you provide the user with a UI for customizing their reports (setting the date range for the report or deciding whether they want to see a detail or summary report for example). Rather than demonstrating how to build a UI (which is a VB procedure outside the scope of this tutorial) the next section shows you how to customize the report by hard-coding the modifications. With a UI, you would pass your user's selections in place of the hard code.


Write the code that does the modifications

This report is currently based on all regions. We'll modify the selection criteria to include only data from the USA. But first you may need to add a reference to
your project.

  1. Close the Crystal Report Viewer.
  2. From the Project menu select References.
  3. Check the Microsoft ActiveX Data Objects Recordset 2.0 Library and click OK.
  4. Double-click Form2 from your Project Explorer to open it. This form contains the Report Viewer. Double-click on it to see the code in the main window. It should look something like this:

This code should appear in the General Declarations section.

Dim Report As New CrystalReport1

This code should appear in the Form_Load event procedure. It tells the viewer what report it should display and then it tells it to display (view) the report.

Private Sub Form_Load()

            Screen.MousePointer = vbHourGlass
            CRViewer1.ReportSource = Report
            CRViewer1.ViewReport
            Screen.MousePointer = vbDefault

End Sub

This code should appear in the Form_Resize event procedure, it resizes the viewer every time the form is resized.

Private Sub Form_Resize()

            CRViewer1.Top = 0
            CRViewer1.Left = 0
            CRViewer1.Height = ScaleHeight
            CRViewer1.Width = ScaleWidth

End Sub
  5. To add selection criteria to the report. Edit the "Form2" declarations and "Form_Load" procedure to look like this:

Dim Report As New CrystalReport1

Dim rs As New ADOR.Recordset

Private Sub Form_Load()

Screen.MousePointer = vbHourGlass

rs.Open "Select * from customer where country = 'USA'", _"xtreme sample database"

Report.Database.SetDataSource rs,3,1

CRViewer1.ReportSource = Report

CRViewer1.ViewReport

Screen.MousePointer = vbDefault

End Sub

This adds a query to select only the records with "USA" in the "Country" field. The recordset that results from that query will be passed to the report engine and the results displayed.

  6. Run the report again to see the changes. Your report should only contain USA data.
  7. Now we'll add a text object to the report and manipulate it using code. In the main Report Designer window, right-click just to the right of the graph in the Report Header pane and point to Insert, then select Text Object.
  8. Move the text object just above the pie graph. You may have to move the graph down a bit first. Make note of the Name in the Properties window. In this example, the name is "Text5" but the name in your project may be different.
  9. Now we'll set the contents of the text object you just added. Open the "Section5" code for editing in the Text Object by double-clicking on the Report Header [Section5] and add some code to the "Section5" "Format" procedure as shown.

Private Sub Section5_Format(ByVal pFormattingInfo As Object)

Text5.SetText "Here is some text from my app"

Text5.Font.Italic = True

Text5.Font.Bold = True

Text5.Font.Size = 14

End Sub

  10. This will set the text object, change the font to Italic, Bold 14 point and display the results. Run the report again to see the changes.

To complete this exercise, you'll now add some event-driven code to explore how you can make the run time viewer control more interactive.

  11. With the Form 2 code window open, use the Object and Procedure list boxes to select the "CRViewer1" object and add the "DrillOnGroup" and "PrintButtonClicked" procedures to the "Form2" code. Edit these new procedures as shown below:

Private Sub CRViewer1_DrillOnGroup(GroupNameList As
Variant, ByVal DrillType As
CRVIEWERLibCtl.CRDrillType, UseDefault As Boolean)

MsgBox "You're drilling down on the " &
GroupNameList(0) & " group!"

End Sub

Private Sub CRViewer1_PrintButtonClicked(UseDefault As Boolean)

MsgBox "You clicked the Print button!"

End Sub

  12. The "DrillOnGroup" procedure is triggered when the user double-clicks on any graph pie slice or report summary field. When this occurs, the text shown will appear in a message box. The "PrintButtonClicked" procedure works similarly when the viewer Print button is clicked. Try both of these procedures to make certain your code works as expected.

Now that you've seen a few simple ways to modify a report, you may want to explore some of the other properties and events in the report engine that you can use in your application. For more sophisticated programming examples, consult the sample applications. For more details on specific methods, properties, or events, use the VB Object Browser or consult the Crystal Reports Developer's Help (CrystalDevHelp.chm) or the Report Designer Component Help (Crrdc.hlp).


RDC Data Access

This section explains data access through the Report Designer Component (RDC), and describes how to connect to a data source through the Data Explorer. It also provides information on Active Data, the Microsoft Data Environment, and the database drivers used by the RDC.

Click the appropriate link to jump to that section:

  • Overview
  • The Data Explorer
  • Active Data Sources
  • Data Environments
  • Database Drivers


Overview

In response to the question, "What data can I use when building reports in the RDC?", the answer is, "You have virtually no limitations." The RDC has been designed to use virtually any data source with minimal work on your part.

The Report Designer Component supports data access through Data Access Objects (DAO), Remote Data Objects (RDO), and ActiveX Data Objects (ADO). Through these three access methods, you can connect to most ISAM, ODBC, and SQL data sources available to Windows applications. In addition, you can create DAO Recordsets, RDO Resultsets, or ADO Recordsets in Visual Basic, then replace the data source used by a report at runtime by calling the SetDataSource method of the RDC runtime Report object.

The Report Designer Component also provides the ability to design reports based on Data Definition files, text files that define the fields, and field types of a database without actually serving as a source of data. Using Data Definition files, you can design a report without depending on the existence of a database at design time, then dynamically create the data at runtime and assign it to the Report object of the Report Designer Component.

If you have installed the full Crystal Reports product, you also have the ability to use the Report Designer Component to connect to any data source that Crystal Reports can connect to. In such a case, the Report Designer Component implements the Crystal Reports user interface that you are already familiar with, so you can quickly connect to any existing data.

Finally, the Report Designer Component also supports Data Environments in Visual Studio 6.0.

Probably the best way to cover all of the data sources is to take a brief look at the Data Explorer dialog box. This dialog box appears when you select Add Database to Report or Set Location, and it lists data source options in a hierarchical tree view.

Visit the Library on the Seagate Software web site to get documentation and knowledge base articles about data access.


The Data Explorer

The top three nodes in the Data Explorer were designed to make it more efficient for you to return to favorite data sources, current connections, or data sources you have used in the past. Those nodes are all intuitive, and they are discussed in depth in the Crystal Reports User's Guide. We'll be discussing the bottom three nodes in this section.


ODBC

The first of these nodes, ODBC, shows a list of ODBC data sources that you have already configured for use. These are local and remote data sources that are not accessed through an object model such as ADO or DAO. The Report Designer Component can use the same database drivers for these data sources that are available through Crystal Reports.

Note: To use these drivers, you must install the full Crystal Reports product.

You can either use an existing data source or create a new one by selecting the Create New Data Source option. If you select, Create New Data Source, the RDC displays a Wizard that leads you through the creation process.

You will need to supply:

  • the type of data source you want to create
  • the driver you want to use
  • any driver-specific information that is required.

If you are setting up a machine-independent File Data Source, you will also be asked to supply the name of the file data source you want to save the connection to.

Once you've supplied this information, the Wizard sets up the data source for you.

To connect to an existing ODBC data source
  1. Choose the data source.
  2. Choose the table(s) that contain the data you want to use.
  3. Link the tables (if required) using the Visual Linking Expert.

Once you have done this, the RDC lists the tables you have selected and the fields available in each table under the Database Fields node in the Field Explorer on the left side of the Designer.

Then drag the fields you want onto your report and position them where you want them.

Database Files

This node lists standard PC data sources that reside locally. If your database isn't listed, browse for your file using the Find Database File option.

More Data Sources

Use the More Data Sources node to select data sources that can be accessed through OLE DB and native drivers. This includes:

  • Microsoft Active Data sources (ADO, DAO, RDO)
  • Exchange folders
  • Data stored on the local file system
  • Mailbox Administration Files from Exchange
  • IIS and Proxy server log files
  • NT Event logs
  • Direct OLE DB connections
  • Outlook folders
  • Web IIS Log Files


Active Data Sources

When you choose any of the Active Data data sources (ADO, DAO, RDO, or Data Definition Files), the RDC displays the Select Data Source dialog box with the appropriate tools enabled.

ADO

ActiveX Data Objects is the new data connection technology designed to provide a common interface for working with relational databases, mail messaging, event logs, and most any other form of data storage. ADO can be used to connect to any ODBC or OLE DB compliant data source when you design your report in the Report Designer Component.

The resulting ADO Recordset is not directly available from the Report Designer Component, but it can be replaced by alternative Recordset objects. For example, if your Visual Basic application allows users to make choices that can affect the set of data displayed by a report, simply create a new ADO Recordset at runtime, then pass it to the Report Designer Component using the SetDataSource method. The only restriction is that the fields in the new Recordset match the fields originally used to design the report. For more information on using the SetDataSource method, see SetDataSource method.

ADO is the most flexible option for data access. It provides a means of connecting to all kinds of data, including mail messaging, event logs, and Web server site data. In addition, it has been designed, ultimately, to replace DAO and RDO.

  • If you are creating new applications using Visual Basic, you should strongly consider ADO for your data connections.
  • If you are working with Visual InterDev for developing web sites, you have an additional advantage of being able to use ADO with Active Server Pages.


DAO

Data Access Objects (DAO) is designed primarily for use with local and ISAM (Indexed Sequential Access Method) data sources created through applications such as Microsoft Access, Microsoft FoxPro, and Borland dBASE. Although DAO can be used to connect to ODBC data sources, RDO and ADO provide more powerful options for such data. However, DAO is the oldest of the three technologies, giving it the advantage of being familiar to many Visual Basic programmers. As a result, DAO is also frequently found in existing applications, and applications created with older versions of Visual Basic.

If you are adding the Report Designer Component to a Visual Basic application that already uses DAO, or if you are connecting to a local data source such as an Access or dBASE file, you should consider using DAO to design your reports. Experienced Visual Basic programmers who are familiar with the DAO object model may also want to stick with a known technology. However, if you are working with ODBC or other remote data sources, RDO and ADO may be a better solution.

Once you design your report in the Report Designer Component, information about the connection to your DAO data source is stored with the report, and cannot be accessed directly. However, you can change the data displayed by a report by changing the data source at runtime using the SetDataSource method. A DAO Recordset object may be passed to the report through this method. Keep in mind, though, the Recordset must have fields identical to those in the original data source used at design time.


RDO

Remote Data Objects (RDO) is designed specifically for working with remote data sources. This includes ODBC and most common SQL database systems. In fact, RDO acts as an object-oriented wrapper around the ODBC API. The flexibility of ODBC is available to Visual Basic programmers through the simplicity of a COM based object model. Already a common choice for developers of client/server systems, RDO allows the execution of stored procedures and the processing of asynchronous operations, meaning your users can continue to work while your application processes a data query in the background.

The basic object used to manipulate data in RDO is a Resultset (specifically, the rdoResultset object). A new Resultset can be defined in your Visual Basic application and passed to the Report Designer Component at runtime using the SetDataSource method. The RDO data source used to initially create your report at design time, however, is not available for direct manipulation. Instead, information about the connection to the data source is stored inside the instance of the Report Designer Component that you add to your application. By creating a new Resultset at runtime, though, and passing the Resultset to the Report Designer Component, you can control the data in a report based on user requests and responses.

RDO provides a powerful connection to remote data sources through ODBC. If you are designing a client/ server application, or any application that needs to connect to a large database system such as Microsoft SQL Server, Oracle, or Sybase Adaptive Server, RDO can provide a strong solution. However, RDO limits your application to standard relational database systems. Other sources of data, such as e-mail and messaging servers, system logs, and Internet/intranet server logs are unavailable to RDO. Developers designing web-based applications using Visual InterDev would also be served better by ActiveX Data Objects (ADO).


Crystal Data Object (CDO)

If you develop applications that produce data that does not exist outside of the running application (applications monitoring system or network resources, for example), you can take advantage of the most powerful reporting features in the industry via the Crystal Data Object (CDO). Using CDO, the Active Data Driver, and the Report Design Component, you can create reports that are instant and up to date, without first having to dump the data to a separate database.

The Crystal Data Object is an ActiveX DLL that can be accessed from any Windows development environment that supports ActiveX. By creating a Rowset object, similar to a Recordset, and filling it with fields and data, you design a virtual database table that passes as an ActiveX data source to the Crystal Active Data Driver. Once the CDO Rowset has been created, it can be used just like any other active data source such as DAO or ADO.

CDO, like DAO and ADO, is based on the Component Object Model (COM). Any development environment that supports COM interfaces can dynamically generate a set of data for a report without relying on a database that exists at design time.

Note: The Crystal Data Object does not support Memo or BLOB fields.


Crystal Data Source Type Library

The Crystal Data Source Type Library, like Crystal Data Objects, provides a
means for designing customized data sources that can be reported off of using the Active Data Driver. Crystal Data Source, however, unlike CDO, is a type library
with an interface that can be implemented in a standard Visual Basic class. Once implemented, the Crystal Data Source interface allows you to manipulate data fully, much like you would manipulate a standard Recordset object in ADO or DAO.

Note: The Crystal Data Source type library is designed for Visual Basic 5.0 or later.

Keep in mind, though, once you add the Crystal Data Source interface to your class, you must implement all methods and properties exposed by the interface.


CDO vs. the Crystal Data Source Type Library

While CDO and the Crystal Data Source Type Library have some similarities, they have been designed as solutions to different data access problems:

  • If you need to implement a complete data source in your application that allows runtime movement through records and fields, or if you intend to implement your data source as a separate ActiveX component, consider using the Crystal Data Source Type Library.
  • If you need to create a quick and simple means of storing a large amount of data in a convenient package for reporting on, and the data will remain inside the same application as the reporting functionality, then use Crystal Data Objects.


Data Definition Files

A data definition file is a text file that contains information about the kind of data to place in a report instead of information about an actual data source.

  • At design time, you can build reports by pointing the Active Data Driver at a data definition file.
  • At runtime, point the Active Data Driver to an actual data source and the RDC builds your report from that new data.

While data definition files provide great flexibility in your reporting, and they are still supported in Crystal Reports, they have been superseded with a more elegant technology, Unbound Fields.


Data Environments

Data Environments (introduced with VB 6) allow for interactive creation of hierarchical ADO Objects at design time, and easy access to data at run time. Through the Data Environment Designer you create Data Environment objects to connect with Data sources (Connection Objects), and access data from those sources (via Command Objects) at design time and run time.

You can use a data environment as a data source for reports you create with the Report Designer Component. If your project includes a data environment, the Report Designer Component will allow you to select the data environment as a data source at design time. Runtime reports make full use of the data exposed by a data environment by working with the standard connection, command, or recordset objects provided, much like working directly with an ADO object.

Microsoft Data Link (UDL) files

The Report Designer Component now supports Microsoft Data Link (UDL) files.

Microsoft Data Link Files are comparable to File DSNs in ODBC. UDL files stores connection information to be used by the OLE DB layer. UDL's are available with OLE DB 2.0, which is installed by MDAC 2.x.

To create a UDL file
  1. Right-click on the Windows desktop, choose "New" from the popup menu and then choose "Microsoft Data Link". A new UDL file will appear on the desktop. By default, it will be called "New Microsoft Data Link.UDL". You can rename this file.
  2. Double-click, or right-click, and choose Properties on this icon to configure the connection. Select the appropriate OLE DB provider in the Provider tab before entering information in the Connection tab. The template for the Connection tab changes based on the OLE DB provider used.

For more information on how to use UDLs, see the Microsoft Data Link help file, "msdasc.hlp".


Report templates using unbound fields

The RDC now enables you to create report templates based on unbound field objects. Then, using minimal code, you can bind those field objects to a data source (or one of several data sources) at runtime. The Report Engine uses the data type and the Name property of the unbound field object to match it with a data field in the recordset.

This technology replaces the need for data definition files. Data definition files are still supported in the Report Designer Component however. For additional information on using Unbound Fields, see Using fields that bind to data sources only at runtime or the Unbound fields and Pro Athlete Salaries sample applications found in the C:\Program Files\Seagate Software\Crystal Reports\Samples\En\Code\Visual Basic folder.


Database Drivers

For the Report Designer Component to get data to display on the report, it uses a database driver. That driver may be a native driver such as Seagate's native Microsoft Access driver, or it may be an ODBC or an OLEDB driver. Each of these drivers is a separate DLL.

These drivers architecturally work the same way: the Report Designer Component accesses the database for the data it needs.


Crystal Active Data Driver

The one driver that stands out is the Active Data driver (P2smon.dll (32-bit)). The difference with this driver is that it is not intended to be used to connect to your database. Instead, this driver works with recordsets.

Most database applications that you might create use recordsets to send data back and forth between the application and the database. With the Active Data driver, you would pass a populated recordset object, which is sitting in memory, to the Crystal Report Engine. The Report Engine then reads the recordset object to populate the report instead of reading the records in the database itself.

Passing the Recordset

For Crystal Reports to use the recordset in memory, you need to:

  • declare the recordset
  • run the query
  • extract the data.

This recordset can be of type ADO (Data Environment), DAO, RDO, or CDO. The syntax involved in passing a recordset to a report differs depending on the component being used. Refer to the Crystal Reports Developer's Help (CrystalDevHelp.chm) and the Report Designer Component Help (Crrdc.hlp) for more information.

Note: You must pass a recordset to the report. If you do not pass a recordset, the Report Designer Component will attempt to connect directly to your database.

  • If you have an unsecured database such as Microsoft Access, the report will work, but the driver is not being used the way it is intended to be used.
  • If the database is secured like a Microsoft SQL Server database, then an error message stating "Server not yet opened" will be displayed because a password was not supplied in order for the report to log on to the database.


SetDataSource method

The SetDataSource method is designed for reports using the Active Data driver. The Method is used to provide information about a data source to the database driver associated with a Database object. For example, if the Crystal Active Data Driver has been used to design the report, this method can be used to provide an active data source for the report, such as a DAO, ADO, or RDO Recordset or a CDO Rowset.


When RDC uses the Active Data Driver

There are three times that the RDC automatically uses the Crystal Active Data Driver:

  • When you use the Project button on the Data tab of the Report Expert to select your data source, the RDC will automatically use the Active Data Driver.
  • When you choose one of the Active Data options from the More Data Sources node in the Data Explorer, the RDC will also use the Active Data Driver.
  • When you use the new methods AddADOCommand or AddOLEDBSource, the RDC will automatically use the Active Data Driver. Both of these methods require you to supply an active ADO connection.


Determining if the RDC is using the Crystal Active Data Driver

If you are having a problem with your data connection and you want to make certain that you are using the Crystal Active Data Driver:

  1. Right-click the empty space beneath the field tree in the Field Explorer at the left of the RDC Designer.
  2. Select Set Location from the shortcut menu when it appears.
  3. When the Set Location dialog box appears, look at the Server Type at the bottom of the dialog. If the RDC is using the Active Data Driver, the server type will read Active Data and then give the active data type (For example, ADO, DAO, etc.).

Note: Alternatively, you can select Convert Database Driver from the shortcut report. When you make this selection, the driver currently in use will be grayed out yet visible.


Understanding the RDC Object Model

This section provides you with an understanding of the Report Designer Component (RDC) Object Model through a high-level overview of how a report is created. The overview is then related to the primary objects and collections contained in the RDC Object Model. More detailed information on a number of the objects, collections, and events is available at the end of the section.

Click the appropriate link to jump to that section:

  • Overview
  • The Application Object
  • The Report Object
  • The Database Object
  • Object Considerations
  • Collection Considerations
  • Event Considerations


Overview

The Report Designer Component is a dual interface object model based on Component Object Model (COM) technology, a standard that allows applications and component objects to communicate with one another. Because the standard doesn't specify how components are structured, but defines only how they communicate with one another other, the RDC can be used in any development environment that supports COM—such as Visual Basic, Visual C/C++, Visual InterDev, etc.

Note: Visit the Library on the Seagate Software web site to get documentation and knowledge base articles about the Report Designer Component Object Model.


A high level overview

The RDC is similar in operation to the Form designer in VB: it enables you to create instances of various classes visually.

  • You design a form by positioning controls where you want them to appear and then setting their properties.
      • Each of these controls is actually an instance of a class. A command button is an instance of one class. A text box is an instance of another.
  • You design a report in the same way, by positioning objects where you want them to appear and then setting their properties.
      • Each of the objects in your report is an instance of a class. A Section is an instance of one class. A text object is an instance of another.

A new report, by default contains five section objects: the Report Header (RH) section, the Page Header (PH) section, the Details section, the Report Footer (RF) section, and the Page Footer (PF) section. The sections are numbered in consecutive order from top to bottom. The top section is one; the bottom section is five. All of these sections together make up the Sections collection. The Sections collection is indexed with a one-based index.

Each of these sections has a single event: Format. The Format event is fired whenever a pass is made through the section as the report is being created. By trapping the format event for a section, you can manipulate the section or any of the objects you place in the section whenever the section is fired.

  • Manipulating the section involves actions such as setting its background color or its height.
  • Manipulating an object involves actions such as changing a font color in a field object based on a condition being true or changing the report title in response to user input.

You can do just about anything with the report at runtime, with a minimum of code, and all within the VB IDE.

At this very basic level:

  • You can place objects in your report.
  • You can manipulate the objects as needed in response to various events.


The next level

A report can have more than five sections. You can create these sections yourself if you need additional sections. The RDC will create some for you whenever you group or summarize data.

Sections are numbered consecutively as they are created.

  • The first new section created is section 6.
  • The second new section is 7, and so forth.

When sections are created, they are added to the Sections collection and indexed appropriately.

You can place a variety of Report Objects in the sections of your report.

  • If they are Field Objects, they could be one of many kinds of fields including database fields, formula fields, parameter fields, group name fields, or many others as well.
  • If they are Subreport objects, they can each be viewed as a separate object with its own set of properties. But each subreport is itself a report, and as a report it can contain virtually all of the same kinds of different objects that it's parent report contains.
  • If they are Cross-tab objects, they too can be viewed as separate objects or as specialized reports that themselves contain a variety of different objects.

With Subreport objects and Cross-tab objects, you can change the properties of the objects themselves (Subreport Name, Cross-tab Name) and you can change the properties of the objects they contain as well.


The Primary Objects and Collections

The following objects and collections are discussed in the section:

The Application object

The Report object

The Areas collection

The Sections collection

The ReportObjects collection

The FieldDefinitions collection

The Subreport Object

The Database Object

The DatabaseFieldDefinitions collection

The DatabaseTables collection


The Application object

The top level of the object model is the Application object. Since it is at the top, the RDC always expects it to be there, so there's no need to reference it in your code (generally). There are some specific instances where you must reference it. For more information, see The Application Object.


The Report object

Below the Application object is the Report object. The Report object contains many Collections and objects. For more information, see The Report Object.


The Areas collection

The very top Collection in report is the Areas collection. By default it contains five Area objects. This is a special kind of collection that you may not use too often. We'll talk about that when we discuss the next collection, Sections.


The Sections collection

Every report, including a blank report, has Sections. The Sections are the bands in the report where you place the various report objects. By default, a new report, and thus the Sections collection for that report, contains five sections. Each of the five default sections resides in one of the five default areas—five sections:five areas. When you begin with a blank report, Areas and Sections are essentially the same. So there's little need to reference an area unless you have a specific need to do so.

For example, you want to create several of one kind of section. In this example, you want to create several Details sections. In this case, the five areas:five sections relationship is broken. To refer to those Details sections as a unit, you can think of one Details Area now containing several Details sections. When you reference the area, you are referencing all of the sections in that area.

Thus, unless you have a special need, you can think of Sections as having Report for a parent. If you have the need, or if you want to be very specific, you can also think of Sections having Area for a parent. However you think of this part of the object model is fine. As long as you have five sections and five areas, you can access Sections through Areas, or you can go directly to Sections. Your code will work either way. For more information, see The Sections Collection.


The ReportObjects collection

ReportObjects is a collection that can contain many things. With the exception of Areas and Sections, everything else in a report is a report object including Database field objects, Parameter field objects, and Text objects. Note that we used a lower case "r" and "o" for our spelling of "report object". The reason is there is no "ReportObject" in the ReportObjects collection. The ReportObjects collection is just a convenient way to think about these objects and it is useful in your code.

Now many of these objects that are considered to be members of ReportObjects are also members of more specific collections.

  • A SortField object, for example, is a member of the ReportObjects collection. It is also a member of the SortFields collection.
  • A FormulaFieldDefinition object, likewise, is a member of the FormulaFieldDefinitions collection.

You can access an object through the ReportObjects collection or through its namesake collection. This provides you with much flexibility in your coding. See The ReportObjects Collection.


The FieldDefinitions collection

In the ReportObjects collection, many of the members have the word "field" in their names: GroupNameFieldDefinition, ParameterFieldDefinition. Objects that contain the word "field" are also a part of the FieldDefinitions collection. As was the case with ReportObjects, there is no such thing as a generic FieldDefinition in the FieldDefinitions collection. Instead there are specific kinds of fields including FormulaFieldDefinition, SpecialVarFieldDefinition, SummaryFieldDefinition, and others as well.

Following this up the hierarchy, we see that a ParameterFieldDefinition is a member of:

  • its namesake collection, ParameterFieldDefinitions
  • the FieldDefinitions collection
  • the ReportObjects collection.


The Subreport Object

The Subreport Object is part of the ReportObjects collection. A subreport is a report within a report; it is a complete report with its own Areas, Sections, and ReportObjects. Once you access a Subreport object, you manipulate the objects in the subreport the same way you would with objects in the main report. For more information, see The Subreport Object.


The Database Object

The Database object represents a data source for the report. But a data source doesn't mean all the data available. It means only a subset of data that is useful for the report. That subset can be defined as collections of tables and, within each of those tables, collections of fields. When you think about a data source in this way, the data side of the RDC object model becomes clear. For more information, see The Database and Database Tables Objects.


The DatabaseTables collection

The Database object contains a DatabaseTables collection. This collection contains a number of DatabaseTable objects which comprise all the Tables which contain data used in the report.


The DatabaseFieldDefinitions collection

Each DatabaseTable object contains a DatabaseFieldDefinitions collection which holds all of the fields from the table that are available for the report. Each of those fields is called a DatabaseFieldDefinition.


Object Considerations

Seagate Software IMG Holdings, Inc.
http://www.seagatesoftware.com
Support services:
http://support.seagatesoftware.com


The Application Object

Not all development environments support ActiveX designers. Visual C++ and Delphi, for example, are two environments where you can use the functionality of the RDC automation server but you can't add the RDC directly to your projects. In these cases, you must access the Report Designer's Report object by creating an instance of the Application object and then calling the OpenReport method as well.

In other situations, you may need to use separate report files in your application that were created or edited using Crystal Reports. An advantage of using such standalone report files is that through Crystal Reports, you can save report data with the report file, eliminating the need of maintaining a connection to a data source at runtime. In this case you will need to create an instance of the Application object and then call the OpenReport method as well.

The following code sample demonstrates the process of obtaining an Application object and opening a report file in Visual Basic:

Dim CRXApplication As CRAXDRT.Application

Dim CRXReport As CRAXDRT.Report

    Private Sub Form_Load()

       Set CRXApplication = CreateObject("CrystalRuntime.Application")

       Set CRXReport = CRXApplication.OpenReport("C:\Reports\Sales.rpt")

    End Sub

When this code finishes, rpt is a valid Report object and can be used just like any Report object you would obtain through the Report Designer Component.

Note: The sample call to CreateObject above uses a version independent Prog Id for the Report Designer Component. The correct Prog Id for this version of the Report Designer Component is CrystalRuntime.Application.8, but the version independent Prog Id should use the most recent version of the component installed on your system.


The Report Object

Many existing ActiveX object models require declaring and creating a high level object, such as an Application object, before you can work directly with the data. The RDC, however, allows direct access to the Report object, giving you control over your reports with a small amount of Visual Basic code.

Assuming you have added the RDC to a Visual Basic application, and the (Name) property of that component is set to CrystalReport1, you can use code similar to the following to obtain a Report object representing that component:

Example:

Dim cr As CRAXDRT.Report
Set cr = New CrystalReport1
  • The first line declares cr as Report object from the CRAXDRT object library, the Report Designer Component's object library.
  • The second line of code defines cr as a new instance of the report in the CrystalReport1 component in your application.


The Field Object

All relational databases have two standard features: records and fields. Records contain the actual data, while fields define what type of data the records contain.

  • You can control the records through Recordset and Resultset objects exposed by ADO, RDO, and DAO.
  • You can manipulate the fields in the data source through these objects as well.

To manipulate the fields that appear in your report, however, you must either:

  • know the name of each database field you want to manipulate and reference each field directly, or
  • cycle through the fields in the ReportObjects collection to identify those fields that you want to manipulate.

For examples of how to use either of these methods, see Referencing objects in a report.


The Database and Database Tables Objects

All reports must connect to a data source to obtain data. The most commonly used data source is a relational database. The Report Designer Object Model, therefore, has provided objects, properties, and methods specific to working with databases.

The Database object is available directly from the Report object and represents the data source used by the report. This data source can be changed using the Database object's SetDataSource method. In addition, the Database object provides the Tables property, a read-only property that gets the DatabaseTables collection of DatabaseTable objects. You have access to log on information (for password protected systems), database driver names, and database locations through a DatabaseTable object. Use code similar to the following in order to work with the Database and DatabaseTable objects:

Dim Report As New CrystalReport1

Dim tableName As String
Dim dbTable As CRAXDRT.DatabaseTable
Report.Database.Verify() ' Verifies a valid connection to the database
For Each dbTable In Report.Database.Tables
   tableName = dbTable.Name
Next


The Subreport Object

A SubreportObject object is another report inside the original report. Once you have obtained a SubreportObject, you can work with any aspect of it just as if it were a standard Report object.

You can obtain a SubreportObject through the ReportObjects collection. The following example shows you how to iterate through the sections of a report and change the background color of each subreport to magenta.

Dim Report As New CrystalReport1

Dim subReport As SubreportObject

Dim sect As Section

Dim rptObject As Object
For Each sect In Report.Sections
    For Each rptObject In sect.ReportObjects
        If rptObject.Kind = crSubreportObject Then
            Set subReport = rptObject

            subReport.BackColor = RGB(255, 0, 255)

            Set subReport = Nothing
        End If
    Next
Next

Note: Currently, the Crystal Report Designer Component does not support subreports inside of subreports. The report iterations cannot go more than one subreport deep. However, you can have multiple subreports inside the main report.


The CrossTabObject

A CrossTabObject object in the Report Designer represents a single cross-tab in your report. Cross-tabs are specialized subreports. Even if you design your primary report as a cross-tab, it is added to the report page as a separate object inside the report.

You can obtain CrossTabObject objects from a report much like you obtain subreports. Since a CrossTabObject is a report object like a field or a subreport, you can access it through the ReportObjects collection.

CrossTabObjects can be manipulated in the same way as other report objects. However, due to the complexity of this object, few properties and methods are exposed.

The following code searches for cross-tabs in a report and applies formatting features to make them stand out from the rest of the report.

Dim Report As New CrystalReport1

Dim xtObject As CrossTabObject

Dim sect As Section

Dim rptObject As Object
For Each sect In Report.Sections
            For Each rptObject In sect.ReportObjects
                If rptObject.Kind = crCrossTabObject Then
                    Set xtObject = rptObject

                xtObject.BorderColor = RGB(255, 0, 0)

                    xtObject.HasDropShadow = True

                    Set xtObject = Nothing
                End If
            Next
Next


Collection Considerations

The ReportObjects Collection

The ReportObjects collection of a report Section object contains all report objects in that section. Report objects may be Text objects, Fields, Subreport objects, or Cross-tabs. To be able to work with a particular report object, you must first obtain the object, and then determine what type of object it is.

Note: If you want to work with all report objects in a section, consult IReportObject in the Object Browser for a list of properties that are common to all report objects.

Usually, report objects can be addressed directly in your code based on their Name property.

However, if you intend to work with several objects in a section, you need to refer to them through a Section object in the report. The following code locates the last object in the last section of the report and assigns a value to a String variable based on the type of object it is.

Dim Report As New CrystalReport1

Dim sect As Section

    Dim rptObject As Object

    Dim objKind As String

    Dim lastSectWithObject As Integer
lastSectWithObject = Report.Sections.Count

Set sect = Report.Sections.Item(lastSectWithObject)
Do While sect.ReportObjects.Count <= 0
            lastSectWithObject = lastSectWithObject - 1

    Set sect = Report.Sections.Item(lastSectWithObject)
Loop
Set rptObject = sect.ReportObjects.Item(sect.ReportObjects.Count)
Select Case rptObject.Kind
            Case crBlobFieldObject

            objKind = "BLOB field object"
            Case crBoxObject

            objKind = "Box object"
            Case crCrossTabObject

            objKind = "CrossTab object"
            Case crFieldObject

            objKind = "Field object"
            Case crGraphObject

            objKind = "Graph object"
            Case crLineObject

            objKind = "Line object"
            Case crOleObject

            objKind = "OLE object"
            Case crSubreportObject

            objKind = "Subreport object"
            Case crTextObject

            objKind = "Text object"
            Case Else

            objKind = "Unknown object"
End Select

Note: Instead of using the Item property as shown, you can reference a report object directly using its index, for example, ReportOptions(1). You can also reference it directly using its name property by including the report object name in quotes, for example, sect.ReportObjects("Field5") instead of sect.ReportObjects(1).


The Sections Collection

All report objects, such as Fields and Text objects, are contained within Sections. Often, you can obtain these directly by referring to the name property of an object in your code.

Note: There may be times, however, when you need to obtain an object through the report section it is in. At other times, you may have a need to make changes to the section itself.

Every report contains a collection of its sections, stored in the Sections property of the report object. You can access individual sections through this collection. For example, the code below sets the height of the first section of the report (the Report Header) to half an inch (720 twips) and suppresses the second section of the report (the Page Header) so that it will not appear.

Dim Report As New CrystalReport1
Report.Sections.Item(1).Height = 720
Report.Sections.Item(2).Suppress = True

For information on how to obtain and work with other objects within a Section object, such as fields and text objects, refer to The ReportObjects collection.

Each section in a report is itself a collection. The collection contains all of the report objects in that section. When designing your application, be aware that when a section is being formatted, all objects in that section are also being formatted. Also, all other sections and objects outside of the current section are not being formatted. This information can affect how data is displayed in various sections of the report, depending on your code.


Event Considerations

The RDC directly supports four events:

  • AfterFormatPage
  • BeforeFormatPage
  • FieldMapping
  • NoData.

The RDC supports the Format event for the Section object as well. These new events are discussed in detail in the Crystal Reports Developer's Help (CrystalDevHelp.chm) and the Report Designer Component Help (Crrdc.hlp).


The Format event for the Section object

The Crystal Report Designer Component provides a Format event for every section of your report. This allows you to control report formatting and output dynamically at runtime. For example, you can apply conditional formatting during the Format event, based on conditions that exist only at runtime.

The Format event is a standard Visual Basic event that you can program by displaying the Code View of the Report Designer Component. Assuming the Report Designer has been named CrystalReport1 in your Visual Basic project:

  1. In the Visual Basic Project window, select the CrystalReport1 designer from the Designers folder.
  2. Click the View Code button in the toolbar at the top of the Project window. A Code window will appear for the CrystalReport1 designer component.
  3. In the object drop-down list box at the top left of the Code window, select a Section object that you want to apply code to. Notice that Section objects are numbered in the order that they appear on your report, from the top of the Report Design window to the bottom. For instance, if you select the Section1 object, your code will apply to the Report Header section of your report. These Section objects are labeled for you at the top of each section in the Report Designer window.

Notice that when you select a Section object, the Format event is automatically selected for you in the event drop-down list box at the top right of the Code window. Format is the only event available to the Section object.

When writing code for the Format event, keep in mind that not all properties and methods for all objects are available during the Format event. Many properties are available on a read-only basis. If you are not sure about a property or method, refer to the specific property or method name in the Object Browser or the Report Designer Object Model reference section of the Crystal Reports Developer's Help (CrystalDevHelp.chm) and the Report Designer Component Help (Crrdc.hlp).

The Format event receives a single argument from the Report Designer Component. The pFormattingInfo argument is an object of type FormattingInfo. The FormattingInfo object has only three properties:

  • IsEndOfGroup - This property is true if the section being formatted is a Group Footer.
  • IsRepeatedGroupHeader - This property is true if the section being formatted is a repeated Group Header. Repeated Group Headers appear when a group extends to two or more pages, and the group has been formatted to repeat information that appears in the Group Header on the second, third, etc. pages. This property is only true if the Group Header is the second, third, etc. instance of the Group Header. It is false for the original first instance of the Group Header.
  • IsStartOfGroup - This property is true if the section being formatted is a Group Header.

Note: When designing your application, be aware that when a section is being formatted, all objects in that section are also being formatted. Also, all other sections and objects outside of the current section are not being formatted. This information can affect how data is displayed in various sections of the report, depending on your code.

Note: If you are using the Format event to calculate values and you need to carry that value across sections (as in a running total, for example), you will need to use a Report Variable to store your ongoing total. Report Variables are new to Crystal Reports. For further information on Report Variables, please see Report Variables.


The Visual Basic Initialize and Terminate events

In addition to the report-specific events, the Report object can also produce the standard Visual Basic Initialize and Terminate events.

The Initialize event is fired when you first reference the Report object at runtime. For example, your application may contain a global variable that represents the Report object of the Report Designer that you added to your application at design time:

Dim Report As New CrystalReport1

In this case, declaring and setting the Report variable fires the Initialize event. The Terminate event will be fired when this variable is set to Nothing:

Set Report = Nothing

The Initialize event and the Terminate event are fired only once for each Report instance. With that in mind, you can make many changes to your report within the event procedure code for each of these events:

Private Sub Report_Initialize()
   ' Add report initialization code here
End Sub
Private Sub Report_Terminate()
   ' Add report clean up code here
End Sub
  • Use the Initialize event to make broad changes that affect the entire report. For instance, you could assign a new data source using the SetDataSource method.
  • Use the Terminate event to clean-up of any variables or objects that you created during the Initialize event. If, for instance, you created a new ADO Recordset object in the Initialize event, you can use the Terminate event to set this Recordset object equal to Nothing, freeing up system memory and resources.


RDC Programming

This section provides solutions to a number of common runtime challenges. Most of these challenges involve accessing an object and then changing the properties. The section first discusses special considerations when programming with the Report Designer Component (RDC); it then presents the two general methods to access an object in a report or subreport. The examples assume that you have used one of these methods to locate the object of interest in order to concentrate on the special considerations that you may have with each of the various procedures.

Click the appropriate link to jump to that section:

  • Special Considerations
  • Two methods to access an object in a report or subreport
  • Runtime examples


Special Considerations

Object naming considerations

If your project includes other libraries that contain objects with names identical to those found in the Crystal Report Engine Object Library, you will encounter conflicts unless you reference the objects using a prefix that identifies their source. For example, if you have included the DAO Library with the RDC runtime object library in your project, you will find that both libraries include a Database Object. In order to avoid conflicts, you must prefix the objects as follows:

CRAXDRT.Database

for the object from the RDC runtime Object Library, or

DAO.Database

for the object from the DAO Library.

Scope considerations

When you specify a data source using code, it is important you place the code in the appropriate location in your project.Otherwise, you will face "no data" or runtime error situations because the report may be searching for data that has gone out of scope.

By default, the program does not read data into the report until you actually run the report (print it, preview it, etc.). Anything that terminates the connection to the data source before this time will cause out of scope problems.

Typical out-of-scope problems include:

  • Declaring a local object variable for the recordset or resultset in the Form_Load event procedure. While this may seem appropriate, the variable, and thus the data it references, will go out of scope as soon as the form stops loading.
  • Similarly, declaring a local object variable in the Report_Initialize event procedure will go out of scope because the recordset is discarded at the end of the procedure. That procedure ends before any records are read from the recordset.

Both problems can be corrected by declaring the variable for the recordset at the module level.

  • A third problem can occur when you declare a global variable for the report and try to populate it with a recordset that only has procedural scope. The following code provides a good example of this:
Dim CRXReport As New CrystalReport1
Private Sub Form1_Load()

   Call SetData

       CRViewer1.ReportSource = CRXReport

       CRViewer1.ViewReport

    End Sub
Private Sub SetData()

   Dim rs As New ADOR.Recordset

       rs.Open "Select * From Customer", "Xtreme Sample Database"

     CRXReport.Database.SetDataSource rs, 3, 1

    End Sub

In this example, although the CRXReport object is global (for the Form), the rs object exists only for the life of the SetData procedure. Even though it is assigned to the Report object before SetData finishes, the object, and the data that rs represents goes out of scope and is invalid for the Load event. Thus, the code will fail.

This problem can be solved using the ReadRecords method. ReadRecords forces the report to read the records into the report so that they are internal to the Report object itself rather than remaining as a separate Recordset object referenced by the report.

Private Sub SetData()

   Dim rs As New ADOR.Recordset

       rs.Open "Select * From Customer", "Xtreme Sample Database"

     CRXReport.Database.SetDataSource rs, 3, 1

     CRXReport.ReadRecords

    End Sub

In this case, the records are read into the report prior to the end of the procedure. Thus, when the procedure ends, the recordset object may be discarded but the records are still available for use.

Index considerations

The various collections in the RDC object model are all one-based, that is, the first member of a collection has index number 1, the second member has index number 2, and so forth. Collection members are indexed consecutively in the order that they are created.

Dual Interface considerations

The Report Design Component provides dual interfaces. As a result, development environments such as Visual Basic and Visual C++ can bind with vTable interfaces at compile time, and less robust environments, VBA, ASP, for example, can use the IDispatch interface for runtime-only binding.

It is important that you use the more efficient vTable interface if it is supported by your development environment.

  • When you use vTable binding, you have "early binding" which means the VB compiler can identify syntax errors at compile time when they're easier to identify and fix than when they appear only at runtime.
  • It enables the VB IDE to speed your coding process by providing hints as you code through its "Auto List Members" and "Auto Quick Info" capabilities.

When you work with Visual Basic, always use the more efficient vTable interface as long as you Dim your object variables using specific class names instead of using the more generic "Object" type.


Two methods to access an object in a report
or subreport

Referencing objects in a report

Before you work with a report object, you have to reference it (open it). You can reference a report object either explicitly or implicitly:

  • Referencing the object Explicitly is the easiest and quickest method for referencing a report object. When you use this method, your code can reference the report and its objects directly.
  • Referencing a report object Implicitly is a more generic approach. This approach allows your code to reference the report and its objects indirectly.
  • You can access objects in a report either explicitly or implicitly.

Explicit reference - an object in the report

Assume that in your report you have a field with the Name property "OrderID". Since you know the field name, you can use code similar to this to reference the OrderID field directly.

Dim CRXReport As New CrystalReport1
Dim CRXReportField As FieldObject
Set CRXReportField = CRXReport.OrderID

Note: Now that you have the OrderID field, you can put your code here to work with the properties of that field.

Implicit reference - cycling through the sections

If you are planning to work with a number of different kinds of report objects, you can cycle through the sections, test each of the report objects for kind, and manipulate them as you wish. You can do that using code similar to this:

    Dim CRXReport As New CrystalReport1
    Dim CRXTables As CRAXDRT.DatabaseTables
    Dim CRXTable As CRAXDRT.DatabaseTable
    Dim CRXSections As CRAXDRT.Sections
    Dim CRXSection As CRAXDRT.Section
    Dim CRXSubreportObj As CRAXDRT.SubreportObject
    Dim CRXReportObjects As CRAXDRT.ReportObjects
    Dim CRXReportObject As Object

Note: You put this code in the Form_Load event of the startup form which contains the Report Viewer.

Start by getting the sections from the Main report.

Set CRXSections = CRXReport.Sections

You begin cycling through each section in the main report.

For Each CRXSection In CRXSections

In each section, you get all the objects in the section.

Set CRXReportObjects = CRXSection.ReportObjects

You cycle through the objects.

For Each CRXReportObject In CRXReportObjects

You test the objects to see if they're subreports.

If CRXReportObject.Kind = crSubreportObject Then

When you find a subreport, you get a hold of it.

Set CRXSubreportObj = CRXReportObject

Before you work with an object in a report, you have to reference it (open it).

Implicit reference - through a collection

If you are planning to work with a specific kind of report object, you can access the object by referencing the collection that contains that object. You reference a collection in a report through the appropriate Report property. Those properties, and the collections they get, are as follow:

Property | Gets
Areas | Areas collection (Areas)
Database.DatabaseTables | Database Tables collection
FormulaFields | Formula Fields collection (FormulaFieldDefinitions)
GroupNameFields | Group Name Fields collection (GroupNameFieldDefinitions)
RunningTotalFields | Running Total Fields collection (RunningTotalFieldDefinitions)
GroupSortFields | Group Sort Fields collection (SortFields)
ParameterFields | Parameter Fields collection (ParameterFieldDefinitions)
RecordSortFields | Record Sort Fields collection (SortFields)
Sections | Section collection (Sections)
SQLExpressionFields | SQL Expression Fields collection (SQLExpressionFieldDefinitions)
SummaryFields | Summary Fields collection (SummaryFieldDefinitions)

Once you have the collection, you can cycle through the collection to locate the appropriate object you want. The following example shows you how to access the FormulaFieldDefinitions collection:

You can put this code in the General Declarations.

Dim CRXReport As New CrystalReport1
Dim CRXFormulaField As CRAXDRT.FormulaFieldDefinition

You can put this code in the Form_Load event procedure.

Private Sub Form_Load()

This code gets the collection.

Set CRXFormulaFields = CRXReport.FormulaFields
'You can put your code here to cycle through the collection to get the
specific object you want

Finally you can view the report.

Crviewer1.ReportSource = CRXReport
Crviewer1.ViewReport
End Sub

Referencing objects in a subreport

Before you work with a subreport, you have to reference it (open it). Similar to referencing objects in a report, you can do this either explicitly or implicitly.

Explicit reference - the subreport itself

Assume that in your report you have a subreport with the Name property "Orders". Since you know the subreport name, you can use code similar to this to reference that subreport directly:

Dim CRXReport As New CrystalReport1
Dim CRXSubReport As SubreportObject
Set CRXSubReport = CRXReport.Orders

Note: Now that you have the subreport, you can add code to manipulate the subreport.

Explicit reference - an object in the subreport

Assume that in your report you have a subreport with the Name property "Orders" and that, in that subreport, you have a field with the Name property "OrderID". Since you know the subreport and field names, you can use code similar to this to reference the OrderID field directly:

Dim CRXReport As New CrystalReport1
Dim CRXSubReport As SubreportObject
Set CRXSubReport = CRXReport.Subreport1
Dim CRXSubReportField As FieldObject
Set CRXSubReportField = CRXReport.Orders_OrderID

Now that you have the OrderID field, you can add code to work with the properties of that field.

Please note the special way you reference a field in a subreport by name. You must use:

  • the name of the subreport
  • an underscore
  • the name of the field.

The result, in this example, Orders_OrderID, appears to be a field in myReport with the name Orders_OrderID. It is actually a field in the Orders subreport; the program uses dynamic type info to generate these names at runtime. You can find the names by looking at the Project in the Object Browser.

Implicit reference

Though this approach is more complex, it is not bound to a particular report, and the code can be reused with minor modifications for other reports that contain subreports. You can use code similar to the following to access any and all subreport(s) in a particular report.

You can declare the Variables in the General Declarations section of a form.

Dim CRXReport As New CrystalReport1
Dim CRXTables As CRAXDRT.DatabaseTables
Dim CRXTable As CRAXDRT.DatabaseTable
Dim CRXSections As CRAXDRT.Sections
Dim CRXSection As CRAXDRT.Section
Dim CRXSubreportObj As CRAXDRT.SubreportObject
Dim CRXReportObjects As CRAXDRT.ReportObjects
Dim CRXSubreport As CRAXDRT.Report
Dim CRXReportObject As Object

You put this code in the Form_Load event of the startup form which contains the Report Viewer.

You start by getting the sections from the Main report.

Set CRXSections = CRXReport.Sections

You begin by cycling through each section in the main report.

For Each CRXSection In CRXSections

In each section, you get all the objects in the section.

Set CRXReportObjects = CRXSection.ReportObjects

You cycle through the objects.

For Each CRXReportObject In CRXReportObjects

You test the objects to see if they're subreports.

If CRXReportObject.Kind = crSubreportObject Then

When you find a subreport, you get a hold of it.

Set CRXSubreportObj = CRXReportObject

Finally, you open the subreport and treat it as you would any other report.

Set CRXSubreport = CRXSubreportObj.OpenSubreport

Note: This is where you put the code for manipulating the subreport.

End If
Next CRXReportObject
Next CRXSection


Runtime examples

The following topics are discussed in this section:

  • Working with Cross-Tabs.
  • Working with Data sources.
  • Working with Formatting.
  • Working with Formulas/Selection Formulas.
  • Working with Grouping.
  • Working with parameter fields.
  • Working with OLE objects.
  • Working with Sorting.
  • Working with Summary Fields.
  • Working with Text Objects.


Working with Cross-Tabs

Modifying a cross-tab at runtime

A CrossTabObject object in the Report Designer represents a single cross-tab in your report. Cross-tabs are specialized subreports. Even if you design your primary report as a cross-tab, it is added to the report page as a separate object inside the report.

CrossTabObject objects can be obtained from a report much like subreports. A CrossTabObject is implemented as a single report object accessible through the ReportObjects collection.

The following code searches for cross-tabs in a report and applies formatting features to make them stand out from the rest of the report.

Dim CRXReport As New CrystalReport1

Dim CRXXtObject As CRAXDRT.CrossTabObject

Dim CRXSection As Section

Dim CRXReportObject As Object
For Each CRXSection In Report.Sections
    For Each CRXReportObject In sect.ReportObjects
        If CRXReportObject.Kind = crCrosstabObject Then
            Set CRXXtObject = CRXReportObject

            CRXXtObject.BorderColor = RGB(255, 0, 0)

            CRXXtObject.HasDropShadow = True

            Set CRXXtObject = Nothing
                End If
            Next
Next

Although cross-tabs are much like subreports, because of their specialized handling of data, there are fewer properties available to the CrossTabObject object than to the SubreportObject object. Before trying to use a property with a cross-tab in your report, verify that the property is available to the CrossTabObject object.


Working with Data sources

Changing an ADO data source location - new methods

In Crystal Reports 8, there are two new methods to add ADO data sources to a report:

  • AddADOCommand takes as parameters an active ADO connection and an ADO command object. In this example, a new connection is created to a database, and the resulting recordset is assigned at runtime to the report.
  • AddOLEDBSource takes as parameters the name of an active ADO connection and the name of a table that can be accessed through that connection.

In this example, a connection set up through the VB Data Environment is used as a data source. Both methods can be used with either the VB Data Environment or another data source created at runtime.

Option Explicit
Dim CRXReport As New CrystalReport1

The ADO connection to the local database.

Dim cnn1 As ADODB.Connection
Dim datcmd1 As ADODB.Command

Demonstrate the use of AddADOCommand by opening an ADO data command and adding the data source to the report.

Private Sub cmdADO_Click()
    Dim strCnn As String

Open the data connection.

    Set cnn1 = New ADODB.Connection
    strCnn = "Provider=MSDASQL;Persist Security Info=False;Data
Source=Xtreme Sample Database;Mode=Read"
    cnn1.Open strCnn

Create a new instance of an ADO command object.

    Set datcmd1 = New ADODB.Command
    Set datcmd1.ActiveConnection = cnn1
    datcmd1.CommandText = "Customer"
    datcmd1.CommandType = adCmdTable

Add the datasource to the report.

    CRXReport.Database.AddADOCommand cnn1, datcmd1
End Sub

Adding a data source and a field using AddOLEDBSource

This section demonstrates the use of AddOLEDBSource. One line of code:

  • opens an ADO data source
  • adds the data source to the report, and then
  • adds a field to the report that uses that data source.

In this example, we are using an OLEDB source created in a VB Data Environment.

CRXReport.Database.AddOLEDBSource DataEnvironment1.Connection1,"Customer"

Setting the data source for a subreport

This section describes how to change the database location for different types of data sources

  • Native
  • ODBC
  • Active Data.

You change the database location (change the data source) for a subreport in much the same way as you set the database location for the main report. Before you can change the database location for a subreport, you first need to open the subreport. For more information, see Referencing objects in a subreport.

Once you have opened the subreport you can change the database location. The following examples show you how to do that for a variety of different types of data sources.


Native connection to PC database

If the datasource of the subreport is a PC-type database (for example, MS Access), and the report is connecting natively (P2BDAO.DLL), then you can use code similar to the following:

  1. Get the Tables collection for the subreport.
Set CRXTables = CRXSubreport.Database.Tables
  2. Get the first table from the Tables collection.
Set CRXTable = CRXTables.Item(1)
  3. Finally, set the location of the .mdb file.
CRXTable.Location = "C:\My_Application\My_DB.mdb"


Native connection to SQL database

If the datasource of the subreport is of an SQL-type (for example, MS SQL Server), and the report is connecting natively (P2SSQL.DLL), then you can use code similar to the following:

  1. Get the Tables collection for the subreport.
Set CRXTables = CRXSubreport.Database.Tables
  2. Get the first table from the Tables collection.
Set CRXTable = CRXTables.Item(1)
  3. Finally, set the location of the .mdb file.
CRXTable.SetLogOnInfo <servername>, <databasename>, <userid>, <password>


ODBC connection to a PC or SQL database

If the datasource of the subreport is a PC-type (for example, MS Access) or SQL-type (for example, MS SQL Server), and the report is connecting via ODBC (P2SODBC.DLL), you can use code similar to the following:

  1. Get the Tables collection for the subreport.
Set CRXTables = CRXSubreport.Database.Tables
  2. Get the first table from the Tables collection.
Set CRXTable = CRXTables.Item(1)
  3. Finally, set the location of the .mdb file.
CRXTable.SetLogOnInfo <ODBC_DSN>, <databasename>, <userid>, <password>
Active data connection to a PC or SQL database

If the datasource of the subreport is an active data source (ex. DAO, RDO, ADO, CDO, etc.), and the report is connecting using the active data driver (P2SMON.DLL), then you can use code similar to the following:

  1. Get the Tables collection for the subreport.
Set CRXTables = CRXSubreport.Database.Tables
  2. Get the first table from the Tables collection.
Set CRXTable = CRXTables.Item(1)
  3. Finally, set the location of the.mdb file.
CRXTable.SetDataSource rs, 3

There are many ways that you can access a subreport, and change the database location for a subreport. The above examples are simplified and generic so that they can be used and altered to accommodate an application with any report.

Connecting to OLEDB providers

Each OLEDB provider requires a specific connection string. The following sample connection strings are for use in the "Connection" input box of the "ADO and OLE DB" option on the "Select Data Source" dialog box for the Active Data report expert:

Microsoft Jet 3.51 OLE DB Provider

Provider=Microsoft.Jet.OLEDB.3.51;Data Source=c:\Access\Northwind.mdb

Note: At this time, it is not possible to use secured Access databases in the Crystal Report expert.

      • This OLE DB provider appears to only work with 32-bit Access databases.
      • Notice that the database table and query names do not appear in the drop-down boxes. This has been tracked. The option is to use the SQL textbox instead.

Microsoft OLEDB Provider for SQL Server

Syntax:

Provider=SQLOLEDB;SERVER=SName;DATABASE=DBName; UID=MyID; PWD=MyPWD

Example:

Provider=SQLOLEDB;Server=TechTest;Database=Pubs;UID=Admin;PWD=sa

Microsoft OLEDB Provider for ODBC Drivers

Syntax:
Provider=MSDASQL;DSN=MyDSN;UID=MyUID;PWD=MyPassword
Examples:

For secured Data Sources:

Provider=MSDASQL;DSN=Xtreme Sample Database;UID=Admin;PWD=Password

For non-secured data sources type the DSN:

Xtreme Sample Database

Note: If it is OLE DB that is being used as the provider for ODBC, select the first option of the "Select Data Source" dialog box ("ODBC(ADO)") which uses that specific provider by default.

Microsoft OLEDB Provider for Oracle

Syntax:

Provider=MSDAORA;Password=;User ID=;Data Source=

Example:

Provider=MSDAORA;Password=MyPassword;User ID=Admin;Data
Source=MyOracleServer

Note: It will probably be necessary to re-type the UserID and Password in the corresponding text boxes of the Select Recordset dialog box.

Connecting to a secure Access session

If your reports connect to secure Microsoft Access sessions, you must provide session information at runtime using the SetSessionInfo method of the DatabaseTable object. This method accepts a user ID and password that are passed to the Access session to provide a connection to the database.

Session information must be added to your code using the SetSessionInfo method, even if you specified session information at design time. Session information specified at design time is not stored with the Report Designer Component.

Assuming all tables in your report are from the same secured Access database, you can use code similar to the following to set the Access session information:

Dim CRXReport As New CrystalReport1
Dim CRXTable as CRAXDRT.DatabaseTable
For Each CRXTable In CRXReport.Database.Tables
    CRXTable.SetSessionInfo "user", "password"
Next

Working with secure data in reports

If your report connects to a secure data source that requires log on information, you will not be able to log off of the data source until the Report object has been closed or has gone out of scope. Keep in mind that if you assign the Report object to the ReportSource property of the CRViewer object in the Crystal Reports Report Viewer, the Report object cannot be closed until you assign a new value to the Report Viewer or close the CRViewer object. Thus, you will not be able to log off of a secure data source until the report is no longer displayed in the Report Viewer.


Working with Formatting

Using Report Variables

Certain events, like the OnSectionFormat event, may get fired more than once in a section. For example, a Details section may fire multiple times for a given record if the program is performing "Keep Section Together" calculations for the report. When you are using VB variables that are supposed to increment once for each record (as when you are calculating a running total), you can have problems maintaining state with these multiple firings.

To prevent these problems, the RDC now enables you to declare Report Variables. Report variables are Crystal variables that you can use in your VB code. Report Variables "understand" what's going on in the report and they increment appropriately. This enables you to do more of your coding than ever in VB and still get the results you expect.

There are three methods you use with report variables.

AddReportVariable

You use AddReportVariable to declare a Report Variable. The following code declares four Report Variables:

  • CurrencyVal of the type currency
  • LongVal of the type number
  • DoubleVal of the type number
  • StringVal of the type string.
AddReportVariable crRVCurrency, "CurrencyVal"
AddReportVariable crRVNumber, "LongVal"
AddReportVariable crRVNumber, "DoubleVal"
AddReportVariable crRVString, "StringVal"

GetReportVariableValue

You use GetReportVariableValue to reference the value in a Report Variable. The following code references the value in the Report Variable, CurrencyVal.

CurVal = GetReportVariableValue("CurrencyVal")

SetReportVariableValue

You use SetReportVariableValue to increment a Report Variable. The following code sets the value of the Report Variable CurrencyVal to the value of the expression "CDbl(CurVal) + CDbl(FieldCurrency.Value)".

SetReportVariableValue "CurrencyVal", CDbl(CurVal) +
CDbl(FieldCurrency.Value)

Note that you can only use Report Variables at runtime and that you must use double quotes every time you reference such a variable.


Formatting a section or report object conditionally

You can now do conditional formatting using VB code. Crystal Reports has allowed this in the past with its own formula language but now you can do it in VB code as well.

This Format event is fired each time this section is formatted, so you can get the values of the object and perform a variety of formatting functions.

This first example changes the backcolor of the section itself if the value of the selected field is less than 50000.

Private Sub Section6_Format(ByVal pFormattingInfo As Object)
If Field9.Value < 50000 Then
        Section6.BackColor = vbRed
    Else
        Section6.BackColor = vbWhite
    End If
End Sub

The second example changes the color of the text in the selected field if the value of that field is less than 50000.

Private Sub Section6_Format(ByVal pFormattingInfo As Object)
If Field9.Value < 50000 Then
        Field9.TextColor = vbRed
    Else
        Field9.TextColor = vbGreen
    End If
End Sub


Working with Formulas/Selection Formulas

Passing a Selection Formula at Runtime

When you pass the selection formula to Crystal Reports, you use the RecordSelectionFormula property of the Report object.

Note: Formulas must conform to Crystal Reports' formula syntax.(i.e. strings embedded in single quotes while numbers not, etc.). For Crystal Reports to parse a formula it receives from the application (Visual Basic in this case), the formula must be identical to a formula that you would enter directly into the report designer. You can use the MsgBox function in Visual Basic to verify that the formula string being sent from VB is in a format that can be used by Crystal Reports.

Two ways you can use the RecordSelectionFormula property of the Report object are:

  • Hardcoding: you can copy your code from your report and paste it into the code.
  • Using a variable: you can append the value of a variable onto your code when calling the RecordSelectionFormula property.

CRXReport.RecordSelectionFormula = "{Customer.Region} = 'CA'"

Note: Any dates passed to Crystal Reports must be in Crystal Reports Date format, Date(yyyy,mm,dd).

Passing a Formula at runtime

When passing a value to Crystal Reports, you use the.Text property of the FormulaFieldDefinition object.

First, you create your formula using the Crystal Reports formula language.

  • If you are giving it a string value, you must place a string value in it. This will force the program to treat the formula as a string.
  • A single space inside double quotes is a good idea, since this will not print if left unchanged—yet it holds the string type for when you change the actual value later from VB.

Place the new formula on your report where you would like to display the passed value.

If you will be sending a numeric value or date, again place an appropriate value in the formula in order to establish the data type of the formula.

  • To pass a numeric value to a formula, place 0 in the formula when you create the formula in Crystal Reports.
  • To pass a date value to a formula, place the Today function in the formula.

The following code shows how you can send a title to your report from your VB application. As instructed above, a formula is inserted at the top of the report, and is named Title. It presently contains a space inside quotes, as in " ".

Sub Command1_Click ()
'if we hard-code the title
CRXReport.FormulaFields.Item(1).text = "'Report Title'"
'If we use the value of the Textbox
Text1.Text = "This is a Title"
CRXReport.FormulaFields.Item(1).text = chr(34) & Text1.text & chr(34)
End Sub

The following code changes the value of a numeric formula at runtime.

Sub Command1_Click ()
'if we hard-code the numeric value
CRXReport.FormulaFields.Item(1).text = "9"
'If we use the value of a variable
x = 65
CRXReport.FormulaFields.Item(1).text = x
End Sub


Changing a subreport's record selection formula at runtime

Changing the record selection formula for a subreport is similar to changing it for the main report. Before you can change the record selection formula for a subreport, you first must open the subreport. Please refer to Referencing objects in a subreport for examples of different ways you can access a subreport.

Once you have opened the subreport object, you can use code similar to this to change its record selection formula.

CRXSubreport.RecordSelectionFormula = "{Customer.Last Year's Sales} > 100000"

The subreport acts like any report, where any object, property, and method that is accessible by the Report object is the same for a subreport. The only limitation is that subreports cannot be previewed, printed, or exported as an individual report.


Referencing a report formula using the formula name

The following code sample shows how to reference a report formula at runtime using the formula name instead of referencing the formula by index.

You can put this code in the General Declarations.

Dim CRXReport As New CrystalReport1
Dim CRXFormulaFields As CRAXDRT.FormulaFieldDefinitions
Dim CRXFormulaField As CRAXDRT.FormulaFieldDefinition

You can put this code in the Form_Load event procedure.

Private Sub Form_Load()
Set CRXFormulaFields = CRXReport.FormulaFields

Now you can cycle through the formula fields collection.

For Each CRXFormulaField In CRXFormulaFields

Here you find the formula you require by specifying its name. Note the format that the .Name property returns.

If CRXFormulaField.Name = "{@formula}" Then

Now you set the formula text.

CRXFormulaField.Text = "{Customer.Name}"
End If
Next

Finally, you can view the report.

Crviewer1.ReportSource = CRXReport
Crviewer1.ViewReport
End Sub


Working with Grouping

Changing the existing group's condition field

For this scenario, assume that a report has been created which is currently grouped on the City field (For example, }Customer.City}). To change the condition field for the existing field at runtime, you can use the following code.

Note: This code assumes that you know which field you want to change and that there is only one group in the report.

You can place this code in the General Declarations section.

Dim CRXReport As New CrystalReport1 'The existing report (ActiveX Designer)
Dim CRXDBField As CRAXDRT.DatabaseFieldDefinition

You can put this code in the FORM_LOAD event procedure.

Private Sub Form_Load()

Currently the group is based on the CITY field, but you want to change it to the REGION field. This code accesses the first table to get the 12th field which is the REGION field.

set CRXDBField = CRXReport.Database.Tables.Item(1).Fields.Item(12)

Now you can set the new condition field for the existing group. Since you know that there is only one group in the report, you can reference it by its name "GH".

CRXReport.Areas.Item("GH").GroupConditionField = CRXDBField

Finally, display the report.

CRViewer1.ReportSource = CRXReport
CRViewer1.ViewReport

End Sub


Adding a new group to the report

For this scenario, assume that a report has been created and it does not contain any groups. To add a new group to the report at runtime, you can use code similar to the following:

Note: Please note that using this method will not display the group name on the report.

You can place this code in the General Declarations section.

Dim CRXReport As New CrystalReport1 'The existing report (ActiveX Designer)
Dim CRXDBField As CRAXDRT.DatabaseFieldDefinition

You can place this code in the FORM_LOAD event procedure.

Private Sub Form_Load()

For this example, you want to add a group that is based on the REGION field. This code accesses the first table to get the 12th field, which is the REGION field.

set CRXDBField = CRXReport.Database.Tables.Item(1).Fields.Item(12)

Now you can add the new group to the report. Please note that:

  • 0 is the GroupNumber in case you add more than one group
  • CRXDBField is the ConditionField
  • crGCAnyValue is the condition on which the group changes
  • crAscendingOrder is the SortDirection
CRXReport.AddGroup 0, CRXDBField, crGCAnyValue, crAscendingOrder

Finally, display the report.

CRViewer1.ReportSource = CRXReport
CRViewer1.ViewReport
End Sub


Adding a group sort field

This scenario requires a report that already contains a group which also must contain a summary field.

A Group Sort Field can only exist if the group contains a summary field, because that summary field is what the Sort is based on. In this example, the report is grouped on {Customer.Region} and the summary field is the "SUM of Customer.Last Year's Sales (Currency)".

To add a group sort field you can use code similar to the following:

  1. Place this code in the General Declarations section.
Dim CRXReport As New CrystalReport1 'The existing report (ActiveX Designer)
Dim CRXSortFields As CRAXDRT.SortFields
Dim CRXSummaryField As CRAXDRT.SummaryFieldDefinition
  2. Place this code in the FORM_LOAD event procedure.
Private Sub Form_Load()
  3. This code gets the SortFields collection for the groups:
Set CRXCRXSortFields = CRXReport.GroupSortFields
  4. Get the first Summary Field which is the '"SUM of Customer.Last Year's Sales (Currency)".
Set CRXSummaryField = CRXReport.SummaryFields.Item(1)
  5. Now add the Group Sort Field.
CRXSortFields.Add CRXSummaryField, crDescendingOrder
  6. Finally, display the report.
CRViewer1.ReportSource = CRXReport
CRViewer1.ViewReport

End Sub


Modifying a group's sort direction at runtime

You can change a group's sort direction through the SortDirection property of the Area Object. To change a group's sort direction you can use code similar to the following:

Note: All the samples are based on the sample database, XTREME.MDB, which is installed by Crystal Reports.

  1. Put this code in the General Declarations section.
Dim CRXReport As New CrystalReport1
  2. Put this code in the FORM_LOAD event procedure.
Private Sub Form_Load()

The Item parameter "GH1" refers to the first group header; to access the second group header you would use "GH2" This line of code sets the SortDirection to descending.
CRXReport.Areas.Item("GH1").SortDirection = crDescendingOrder
  3. Finally, view the report.
CRViewer1.ReportSource = CRXReport
CRViewer1.ViewReport
End Sub


Working with parameter fields

Crystal parameters and stored procedure parameters and are both set through the ParameterFieldDefinition Object. The following sample code passes four parameters to a report. The Main Report and the Subreport each have a Stored Procedure and a Crystal Parameter.

This code can go in the General Declarations Section.

Private Sub Command1_Click()
Dim CRXParamDefs As CRAXDRT.ParameterFieldDefinitions
Dim CRXParamDef As CRAXDRT.ParameterFieldDefinition
Dim CRXSubreport As CRAXDRT.Report
Set CRXParamDefs = CRXReport.ParameterFields

This code cycles through the ParameterFieldDefinitions collection in the main report.

For Each CRXParamDef In CRXParamDefs
With CRXParamDef
Select Case .ParameterFieldName

It finds and sets the appropriate Crystal parameter.

Case "MainParam"
.SetCurrentValue "Main Report Parameter"

Now it finds and sets the appropriate stored procedure parameter.

Case "[CustomerID]"
.SetCurrentValue "Alfki"
End Select
End With
Next

It opens the appropriate subreport.

Set CRXSubreport = CRXReport.OpenSubreport("sub1")
Set CRXParamDefs = CRXSubreport.ParameterFields

It cycles through the ParameterFieldDefinitions collection for the subreport.

For Each CRXParamDef In CRXParamDefs
With CRXParamDef
MsgBox .ParameterFieldName
Select Case .ParameterFieldName

It finds and sets the appropriate Crystal parameter for the subreport.

Case "SubParam"
.SetCurrentValue "Subreport Parameter"

Now it finds and sets the appropriate stored procedure parameter for the subreport.

Case "[CustomerID]"
.SetCurrentValue "Anton"
End Select
End With
Next

Finally, it disables parameter prompting so the user won't be prompted for a value.

CRXReport.EnableParameterPrompting = False
CRViewer1.ReportSource = CRXReport
CRViewer1.ViewReport
End Sub


Working with OLE objects

Setting the location of an OLE object

This example demonstrates how you can set the location of an OLE object at Runtime using the SetOleLocation command. The example takes three different OLE objects:

  • a bitmap
  • part of an Excel worksheet
  • part of a Word document.

It cycles through them so the RDC prints a different object each time it formats the Details section.

Option Explicit
Private Sub Report_Initialize()
    Database.Tables(1).Location = App.Path + "\Author.mdb"
End Sub
Private Sub SectionDetails_Format(ByVal pFormattingInfo As Object)

Object to hold the bitmap:

Dim bmpHold As StdPicture
    Dim iModNum As Integer

Calculate an integer to pass in as the object name.

    iModNum = cRecNum.Value Mod 3 + 1

Take an action based on the integer passed in.

    Select Case iModNum

The bitmap object:

    Case 1

Set the variable to a bitmap.
        Set bmpHold = LoadPicture(App.Path & res\SampleBitmap1.bmp")

Set the height and width of the Report object equal to the actual values for the bitmap - the StdPicture object defaults to HiMetric, the Report uses twips.
Set the bitmap on the Report equal to the variable.
        Set cOLEObj.FormattedPicture = bmpHold

Convert from HiMetric to twips.
        cOLEObj.Height = bmpHold.Height * 567 / 1000
        cOLEObj.Width = bmpHold.Width * 567 / 1000

The Excel Worksheet object:

              Case 2
        cOLEObj.SetOleLocation App.Path & "\res\SampleExcel1.xls"
        cOLEObj.Height = 1800
        cOLEObj.Width = 5791

The Word Document object:

Case 3
        cOLEObj.SetOleLocation App.Path & "\res\SampleWord1.doc"
        cOLEObj.Height = 322
        cOLEObj.Width = 8641
    End Select
End Sub


Working with Sorting

Changing the existing sort's condition field

For this scenario, a report is created which is currently sorted on the Customer Name field (For example, {Customer.Customer Name}). To change the condition field for the existing field at runtime, the following code can be used:

'General Declarations
Dim CRXReport As New CrystalReport1
Dim CRXDatabaseField As CRAXDRT.DatabaseFieldDefinition
Private Sub Form_Load()

Currently the sort is based on the Customer Name field and the application is to change it to the Last Year's Sale's field. This field must be present on the report. The code accesses the first table to get the 8th field.

Set CRXDatabaseField = CRXReport.Database.Tables.Item(1).Fields.Item(8)

There is only one Sort on this report so we will access the first item of the SortFields collection and set the field to the Last Year's Sale's field.

CRXReport.RecordSortFields.Item(1).Field = CRXDatabaseField
CRViewer1.ReportSource = CRXReport
CRViewer1.ViewReport
End Sub


Adding a new sort field to a report

In this example, we're going to add a sort field that currently isn't sorted.

You can put code like this in the General Declarations section.

Dim CRXReport As New CrystalReport1
Dim CRXDatabaseField As CRAXDRT.DatabaseFieldDefinition
Private Sub Form_Load()

Currently there is no sort in this Report. To add the sort field Customer Name, the application must first get the {Customer.Customer Name} field from the Customer Table. This code accesses the first table to get the 2nd field.

Set CRXDatabaseField = CRXReport.Database.Tables.Item(1).Fields.Item(2)

Now add the field to the SortFields Collection and set the Sort Order to ascending.

CRXReport.RecordSortFields.Add CRXDatabaseField, crAscendingOrder

Note: If the SortField is added while the Report is viewing, you will have to refresh the viewer before the new sort will be active. This can be done by clicking the Refresh button in the Report Viewer or refreshing the viewer through code. For example,

    CRViewer1.Refresh
    CRViewer1.ReportSource = CRXReport
    CRViewer1.ViewReport
    End Sub


Working with Summary Fields

How to change summary field kind

This example populates a combo box with the various summary field kind options and then sets a summary field to the kind selected. This code assumes that you have elsewhere declared a variable cr for your report.

Private Sub Form_Load()
Dim i As Integer

Populate the combo box.

cmbSummaryType.AddItem "crSTSum"
cmbSummaryType.AddItem "crSTAverage"
cmbSummaryType.AddItem "crSTSampleVariance"
cmbSummaryType.AddItem "crSTSampleStandardDeviation"
cmbSummaryType.AddItem "crSTMaximum"
cmbSummaryType.AddItem "crSTMinimum"
cmbSummaryType.AddItem "crSTCount"
cmbSummaryType.AddItem "crSTPopVariance"
cmbSummaryType.AddItem "crSTPopStandardDeviation"
cmbSummaryType.AddItem "crSTDistinctCount"

Get the SummaryFields collection.

Set CRXSummaryFieldDefinitions = CRXReport.SummaryFields
txtCount = CrystalSummaryFieldDefinitions.Count

Cycle through the collection.

For i = 1 To CRXSummaryFieldDefinitions.Count
    Set CRXSummaryFieldDefinition =

CRXSummaryFieldDefinitions.Item(i)
    lstFieldDefinition.AddItem CRXSummaryFieldDefinition.Name
Next i
End Sub

Change the summary field kind.

Private Sub lstFieldDefinition_Click()
     Set CRXSummaryFieldDefinition =
CRXSummaryFieldDefinitions.Item(lstFieldDefinition.ListIndex + 1)
     With CRXSummaryFieldDefinition
        cmbSummaryType.Text = cmbSummaryType.List(.SummaryType)
        txtKind = .Kind
        txtName = .Name
        txtNumberofBytes = .NumberOfBytes
        txtValue = OnFormat
        txtValueType = .ValueType
      End With
End Sub


Working with Text Objects

Simple and complex text objects

There are two types of text objects: simple and complex.

  • Simple text objects are processed internally by the report engine.
  • Complex complex text objects are handled by CRPAIG32.DLL.

Only complex text objects can handle carriage returns and line feeds.

If you want to use carriage returns and line feeds in your text object, you will need to force the text object to be complex. To do this, double-click on the text object to edit it and enter a carriage return (press the enter key) inside of it. Then, when carriage returns and line feeds are passed to the text object through your code, the RDC will process them properly.


Changing the contents of a Text Object

You can use text objects in a variety of different ways:

  • You can use a text object in a simple way to personalize a report based on your users' input (changing the report title, for example).
  • You can also use a text object to display the results of complex operations on database data.

Text objects are very flexible and powerful reporting tools.

To change the contents of a text object you use the SetText method.

  • The Text property of the object model's TextObject gives you information about the existing value; it is a read-only property however.
  • To assign a new value to the property, you must use the SetText method.

Note: The following examples change the contents of a Text object during the Load event of the Form containing the Crystal Report Viewer ActiveX control. This is especially important if the value of your text object is dependent on data in your data source. Since this is also a common place to change the data source used by a report, changing values in Text objects during the Load event often becomes convenient.

Making a simple text change

This example simply assigns a string to the Text1 object in the report.

Private Sub Form_Load()

    Dim CRXReport As New CrystalReport1

    ' More code here

    CRXReport.Text1.SetText "Here is some text from my app"

    CRViewer1.ReportSource = CRXReport

    CRViewer1.ViewReport

End Sub

Displaying a calculated result

A more complicated technique may be to access data in a database, calculate a new value in Visual Basic, and then display that value through a Text object on the report. In such cases, you can supply a text object for each result when you design your report in RDC Designer. The following code assumes that you have done this:

Private Sub Form_Load()

Set up the variables.

    Dim maxValue As Currency

    Dim maxValueString As String

    Dim CRXReport As New CrystalReport1

    Dim rs As New ADODB.Recordset

Set your data source.

rs.Open "SELECT * FROM Customer", _

"DSN=Xtreme Sample Database;", adOpenKeyset
CRXReport.Database.SetDataSource rs
maxValue = 0

Read the records and calculate the results.

    rs.MoveFirst
    Do While Not rs.EOF
        If rs.Fields("Last Year's Sales") > maxValue Then
            maxValue = rs.Fields("Last Year's Sales")
        End If
        rs.MoveNext
    Loop

Format and assign the results to the text object.

    maxValueString = "The maximum value is " & _

        Format(maxValue, "Currency")
    CRXReport.Text1.SetText maxValueString

Preview the report.

    CRViewer1.ReportSource = CRXReport

    CRViewer1.ViewReport
End Sub

In this example, we are finding the maximum value of the Last Year's Sales field from the new data source, formatting that value as Currency, then displaying a message containing the value through a Text object on the report. As you can see, Text objects provide many options for controlling the output of data in your reports.


Programming the Crystal Report Viewers

The Crystal Report Viewer is a front-end user interface for viewing reports. In this section you will find detailed information on implementing the ActiveX and Java Bean viewers in your application.

Click the appropriate link to jump to that section:

  • Enhancements to the Report Viewer
  • Crystal Report Viewer for ActiveX
  • The Crystal Report Viewer Java Bean


Enhancements to the Report Viewer

The Report Viewer has been enhanced substantially in Version 8:

  • The Report Viewer uses multi-threading. As a result, your users can begin viewing a report sooner, even if the report requires that it all be run before certain values are generated (page numbering, for example, of the style "page 24 of 125"). In such a case, the Report Engine uses place holders for the yet-to-be-generated total page count. When that page count is completed, the Report Engine inserts the missing data into the pages already read.
  • The report's group tree is loaded on-demand. This allows your users to use the tree functionality for navigation even when only a partial group tree has been loaded.
  • You can specify a page number to go to in the report you are currently viewing.
  • You can use the Select Expert and the Search Expert in the viewer to select records and search for specific values using formulas.
  • The Report Viewer supports the use of rotated text in the report.
  • The toolbar for the Report Viewer for ActiveX has a new look.
  • You can customize the Report Viewer by resizing sections of the toolbar, adding custom bitmaps, and more.
  • There is a Help button implemented for applications. Clicking on the Help button can fire an event to your application so it can display the appropriate help.
  • There are over 30 events giving you the ability to make previewing the report a truly interactive activity.

For a better understanding of all the capabilities of the Report Viewer, review the viewer object model (CRVIEWERLibCtl) in the Visual Basic Object Browser.

Note: Visit the Seagate Software Developer Zone web site at
http://www.seagatesoftware.com/products/dev_zone.
Click Support to get links for finding documentation and knowledge base articles about the Report Designer Component.


Application Development with Crystal Report Viewers

Developing applications that display reports on screen is now a straightforward process. Crystal Reports includes the Crystal Report Viewers as easy to use but complex components that can be embedded directly in an application. Once added to an application, reports accessed through the Report Engine Automation Server, the Report Designer Component, or the Crystal Web Reports Server can be displayed right inside your own applications. The Report Viewer retains all of the powerful formatting, grouping, and totalling power of the original report, and your users get access to data in a dynamic and clear format.

Crystal Reports provides two Report Viewers specifically designed for application development: the Crystal Report Viewer for ActiveX and the Crystal Report Viewer Java Bean. Both provide a complete object model for programming and manipulating the Report Viewer at runtime inside your applications. Simply displaying a single report inside the Report Viewer is a simple process requiring only a couple of lines of code. However, if necessary for your application, you have the option of complete control over how the Report Viewer appears and functions.

With the Crystal Report Viewer as a front-end user interface for viewing reports, Crystal Reports development technologies allow you to develop even complex client/server or multi-tier applications that access, manipulate, and display data for intranet systems, workgroups, or any group of people needing clear and informative data on a regular basis. Design robust Business Support systems and Enterprise Information Management applications delivering even the most complex data through the Crystal Report Viewers.

This chapter describes both the ActiveX and Java Bean versions of the Report Viewer in relation to designing applications using Crystal Reports development technologies.


Crystal Report Viewer for ActiveX

The Crystal Report Viewer for ActiveX is a standard ActiveX control that can be added to an application in any development environment that supports ActiveX. Programmers using Visual Basic, Delphi, Visual C++, or Borland C++ programmers all receive the benefit of quickly adding a powerful report viewer to an application with little coding.

As a standard component, the ActiveX Report Viewer exposes several properties at design time, but also provides a complete object model with properties, methods, and events that can be programmed at runtime. The following sections discuss various topics for working with the ActiveX Report Viewer in Visual Basic. If you are using a development environment other than Visual Basic, use these topics as a guideline, but refer to your development software documentation for specific information on working with ActiveX controls.

The Crystal Report Viewer, as an ActiveX control, includes a complete object model for controlling how it appears in an application, and how it displays reports. Simply displaying a report in the Report Viewer window takes little code, but to truly make use of its power requires a broader understanding of how to work with the object model.

Related topics:

Adding the Report Viewer to a Visual Basic project.

Using the CRViewer object.


Adding the Report Viewer to a Visual Basic project

If you create a new report using the Create Report Expert in the Crystal Report Designer Component, the Report Viewer control can be automatically added to a Form in your Visual Basic project. However, there may be times when you need to add the control by hand. In addition, the Report Viewer control can be implemented in other environments, many of which may not support ActiveX designers, meaning the Create Report Expert is unavailable.

Use the following steps to add the Crystal Report Viewer ActiveX control to a Form in your Visual Basic application. This tutorial assumes the Form already exists in your project and is named Form1.

  1. First, you must verify that a reference to the Report Viewer control exists in your project. From the Project menu, select the Components command. The Components dialog box appears.
  2. On the Controls Tab of the Components dialog box, scroll through the list of ActiveX controls until you find Crystal Report Report Viewer.

    Note: If you do not see the Crystal Report Report Viewer control in the list, use the Browse button to locate the CRVIEWER.DLL component in the C:\Program Files\Seagate Software\Viewers\ActiveXViewer directory.

  3. If the check box next to the Report Viewer control is not toggled on, toggle it on now.
  4. Click OK, and the CRViewer control will appear in the Visual Basic toolbox.
  5. Click the CRViewer control on the toolbox, then draw the Report Viewer control on your form by dragging a rectangle across the form with the mouse pointer. An instance of the control will be added to your Form.
  6. Adjust the size and position of the Report Viewer on your form, and use the Properties window to adjust the overall appearance of the control.


Using the CRViewer object

The CRViewer object represents an instance of the Report Viewer control that has been added to your project. If you have created a report using the Crystal Report Designer Component and accepted the defaults for adding the Report Viewer to your project, the Report Viewer control in your application will be named CRViewer1. CRViewer1 can be used in your code as a CRViewer object. For instance, the following code demonstrates a simple technique for assigning a report to the Report Viewer, and displaying it:

CRViewer1.ReportSource = report
CRViewer1.ViewReport

For more information on the properties and methods available with this object, refer to the Report Viewer object model and the CRViewer object.

The topics listed below describe several aspects of the Report Viewer object model and present examples of how to use the Report Viewer objects, methods, properties and events in your Visual Basic code.

  • Specifying a report
  • Working with secure data in reports
  • Handling Report Viewer events
  • Moving through a report
  • Printing the report
  • Controlling the appearance of the Report Viewer
  • Connecting to the Web Reports Server


Specifying a report

The most important task with the Report Viewer control is to specify a report and display it at runtime. This is easily handled with the ReportSource property and the ViewReport method.

Private Sub Form1_Load()
 Dim report As New CrystalReport1
 CRViewer1.ReportSource = report

 CRViewer1.ViewReport
End Sub

In this example, assigning the report and displaying it in the Report Viewer is handled when the Form containing the Report Viewer object is loaded into the application. A reference to the report is first obtained in the form of a Report object representing a Crystal Report Designer Component that has been added to the Visual Basic project.

ReportSource is a property of the Report Viewer's CRViewer object which corresponds directly to the Report Viewer control added to the project. In this case, that control has been named CRViewer1. The ReportSource property can accept a report in the form of a Report Object exposed by the Report Designer Component or the Crystal Web Reports Server.

Finally, the ViewReport method is called. This method has no parameters and has the job simply of displaying the specified report inside the Report Viewer control.


Working with secure data in reports

If your report connects to a secure data source that requires log on information, you must release the Report object from the Report Viewer before you can log off of the data source. This can be done by assigning a new Report object to the ReportSource property, or by closing the CRViewer object. Until this is done, the data source will not be released from the Report object and you cannot log off.


Handling Report Viewer events

The Report Viewer control allows you to write custom code for several events relating to user interaction with both the control window and the report displayed. For instance, if you design a drill down report using the Report Designer Component, your users are likely to want to drill down on detail data. You can provide custom handling of such an event by writing code fort the DrillOnGroup event.

To add event procedures to the Report Viewer control for the DrillOnGroup and PrintButtonClicked events:

  1. In the Visual Basic Project window, select the Form containing the Report Viewer control.
  2. Click the View Code button in the toolbar for the Project window. A code window for the form appears.
  3. In the drop-down list box at the upper left hand corner of the code window, select the CRViewer1 control. (This name will appear different if you changed the Name property of the control in the Properties window.)
  4. In the drop-down list box at the upper right corner of the code window, select the DrillOnGroup event. A procedure appears for handling the event.
  5. Add the following code to the DrillOnGroup event procedure:

    Private Sub CRViewer1_DrillOnGroup(GroupNameList As Variant, _
    ByVal DrillType As CRVIEWERLibCtl.CRDrillType, UseDefault As Boolean)

    MsgBox "You're drilling down on the " & GroupNameList(0) & " group!"

    End Sub

  6. In the drop-down list box at the upper right of the code window, select the PrintButtonClicked event. A new procedure appears for this event.
  7. Add the following code for the new event:

    Private Sub CRViewer1_PrintButtonClicked(UseDefault As Boolean)

    MsgBox "You clicked the Print button!"

    End Sub

The DrillOnGroup event is triggered when a user double-clicks on a chart, on a map, or on a report summary field. The code added to the event procedure will display a message box with the name of the group. The PrintButtonClicked event is fired if the user clicks the print button on the Report Viewer window. Note that any code added to these event handlers replaces the default action of the event. A more practical use of these events would be to display custom dialogs or perform other report related calculations and procedures.


Moving through a report

Often, reports consist of several pages. The Report Viewer control provides, by default, controls that allow a user to move through the pages of the report. However, you may need to implement a system through which your own code controls when separate pages are displayed.

The CRViewer object provides several methods for moving through a report, including methods to move to specific pages:

  • ShowFirstPage
  • ShowLastPage
  • ShowNextPage
  • ShowPreviousPage
  • ShowNthPage
  • GetCurrentPageNumber

And methods for moving to specific groups in the report:

  • ShowGroup
Moving through pages

The first set of methods designed for moving through the pages of a report are straightforward and correspond directly to controls that normally appear on the Report Viewer control window. ShowFirstPage, ShowLastPage, ShowNextPage, and ShowPreviousPage simply switch to the first, last, next, or previous page in the report, respectively. They are all used in the same manner in code:

CRViewer1.ShowFirstPage
CRViewer1.ShowLastPage
CRViewer1.ShowNextPage
CRViewer1.ShowPreviousPage

If the requested page cannot be displayed, for instance, if the last page in the report is currently displayed and ShowNextPage is called, the currently displayed page will be refreshed.

For more controlled movements through the report, ShowNthPage can display a specific page of the report:

CRViewer1.ShowNthPage 5

This method accepts a page number as its only argument. If the selected page number does not exist, for example, page 10 is selected from a 6 page report, then either the last or first page will be displayed, depending on the page number requested.

As a convenience, the GetCurrentPageNumber method has also been included. You can obtain the currently displayed page from within your code at any time using this method:

Dim pageNum As Long
pageNum = CRViewer1.GetCurrentPageNumber
Moving to a specific group

Grouping is a common feature of reports, and, since page numbers can frequently change based on current data, it may be more appropriate to navigate through a report using groups. For example, if a report is grouped by cities within states, and by states within countries, you can include code to display the group for a specific city.


Printing the report

Although the Report Viewer control is designed primarily for displaying reports on screen, users frequently want a hard-copy of the data. The PrintReport method provides a simple means of allowing access to the Windows print features. Simply call the method as below, and Windows can take over.

Dim Report As New Crystalreport1
CRViewer1.ReportSource = Report
CRViewer1.PrintReport


Controlling the appearance of the Report Viewer

By default, the Report Viewer window includes several controls for allowing users to navigate through a report, enlarge the view of a report, refresh the data in a report, and more. There may be applications that you create in which you want to limit a user's interaction, change the look of the Report Viewer window, or provide an alternate means of accessing the same functionality.

For instance, you could turn off the navigation controls in the Report Viewer, then create your own controls to navigate through the report that call the ShowFirstPage, ShowLastPage, ShowNextPage, ShowPreviousPage, and ShowNthPage methods. (See Moving through a report.) For handling such custom features, the Report Viewer object model provides several properties for enabling and disabling different features of the Report Viewer ActiveX control:

  • DisplayBackgroundEdge
  • DisplayBorder
  • DisplayGroupTree
  • DisplayTabs
  • DisplayToolbar
  • EnableAnimationCtrl
  • EnableCloseButton
  • EnableDrillDown
  • EnableGroupTree
  • EnableNavigationControls
  • EnablePrintButton
  • EnableProgressControl
  • EnableRefreshButton
  • EnableSearchControl
  • EnableStopButton
  • EnableToolbar
  • EnableZoomControl

Using these properties requires assigning a value of either True or False. True enables the specified control or feature of the Report Viewer, while False disables it. All controls and features are, by default, enabled.

The following code demonstrates how to disable the entire toolbar for the Report Viewer window:

CRViewer1.DisplayToolbar = False


Connecting to the Web Reports Server

The Web Reports Server provides not only a powerful means of distributing reports across the web, but also provides a report distribution mechanism that can be incorporated into multi-tier applications. By using the Crystal Report Viewer for ActiveX as a client-side report viewer, the Web Reports Server can become a report distribution engine within a larger application that runs over a network.

Connecting to the Web Reports Server requires accessing two new ActiveX components: the WebReportBroker and the WebReportSource. The following samples demonstrate how to connect to the Web Reports Server using Connecting from Visual Basic, and Connecting from VBScript, inside a web page.

Connecting from Visual Basic

The following code is an example of how to connect to the Web Reports Server from Visual Basic and assign a report to the Crystal Report Viewer for ActiveX. This assumes that you have added the ActiveX viewer control to a form named Form1, and the ActiveX viewer control is named CRViewer1.

Private Sub Form1_Load()
    Dim webBroker, webSource

    Set webBroker = CreateObject("WebReportBroker.WebReportBroker")

    Set webSource = CreateObject("WebreportSource.WebReportSource")
    webSource.ReportSource = webBroker

    webSource.URL = "http://<machinename>/scrreports/xtreme/hr.rpt"

    webSource.Title = "Employee Profiles"
    CRViewer1.ReportSource = webSource

    CRViewer1.ViewReport
End Sub
Connecting from VBScript

The following code assumes you have added the Crystal Report Viewer for ActiveX to a web page using the <OBJECT> tag and assigned it an ID of CRViewer.

<OBJECT ID="WebSource" Width=0 Height=0>

    CLASSID="CLSID:F2CA2115-C8D2-11D1-BEBD-00A0C95A6A5C"

    CODEBASE="viewer/ActiveXViewer/swebrs.dll#Version=1.2.0.5"

</OBJECT>
<OBJECT ID="WebBroker" Width=0 Height=0>

    CLASSID="CLSID:F2CA2119-C8D2-11D1-BEBD-00A0C95A6A5C"

    CODEBASE="viewer/ActiveXViewer/swebrs.dll#Version=1.2.0.5"

</OBJECT>
<OBJECT ID="Export" Width=0 Height=0>

    CLASSID="CLSID:BD10A9C1-07CC-11D2-BEFF-00A0C95A6A5C"

    CODEBASE="viewer/ActiveXViewer/sviewhlp.dll#Version=1.0.0.4"

</OBJECT>
<SCRIPT LANGUAGE="VBScript">

<!--

Sub Page_Initialize

    Dim webBroker

    Dim webSource

    Set webBroker = CreateObject("WebReportBroker.WebReportBroker")

    Set webSource = CreateObject("WebReportSource.WebReportSource")

    webSource.ReportSource = webBroker

    webSource.URL = Location.Protocol + "//" + Location.Host + _

        "/scrreports/xtreme/invent.rpt"

    CRViewer.ReportSource = webSource

    CRViewer.ViewReport

End Sub

-->

</SCRIPT>


The Crystal Report Viewer Java Bean

The Crystal Report Viewer Java Bean (or Report Viewer Bean) can be added to an application in any development environment that supports Java (version 1.1). Programmers receive the benefit of quickly adding a powerful report viewer to an application with little coding.

As a standard component, the Crystal Report Viewer Java Bean exposes several properties at design time, but also provides a complete object model with properties, methods, and events that can be programmed at runtime. The following discusses one approach to creating an application using the Crystal Report Viewer Java Bean. It describes the creation of a simple Applet which will allow a report to be viewed from your browser.

This example uses the Bean Box a component of the Bean Developer Kit (BDK) from Sun Microsystems Inc. The Bean Box is not intended to be used for serious application development, rather as a platform for testing Beans interactively at design time, and creating simple applets for run time testing. The Bean Box is available for download from Sun Microsystems.


Adding the Report Viewer Bean to the project

To add the Report Viewer Bean to the Bean Box:

  1. Locate the JAR file called ReportViewerBean.jar in the "Viewers" directory
    (\SeagateSoftware\Viewers\JavaViewerBean).
  2. Either copy the file to the \jars subdirectory of the BDK
    or
    From the Bean Box Select LoadJar from the File menu and specify the pathname of the file.
  3. The Crystal Report Viewer Icon should appear in the ToolBox palette.


Creating a simple applet with the Report Viewer

To add the Report Viewer Bean to the Bean Box Composition window and create an applet:

  1. Click on the Report Viewer Beans name (Crystal Report Viewer) in the ToolBox palette.
  2. Click on the location in the Bean Box Composition window where you want the Report Viewer Bean to appear.
  3. Resize the Report Viewer in the Composition window until you are able to see the controls and report window.
  4. In the Bean Box Property Sheet window you will see the list of Report Viewer Bean properties. These can be set and edited. For example to view a report click on the reportName property. When the dialog box appears enter the URL of a report file (for example: "http://localhost/scrreports/craze/adcont2s.rpt").
    The report should be displayed in the Crystal Report Viewer Report window.
  5. To create a simple applet select MakeApplet from the File menu. This will create an applet which when called from your browser will display the report specified in the reportName property. You will be prompted to specify a directory where your applet and its supporting file will be placed (or the default tmp subdirectory of the beanbox directory).

If you look at the directory containing the applet, you will notice that there are a number of supporting files and directories. Locate the html file (<appletname>.html) and click on it. Your default browser should display the Report Viewer and the report.

The minimum required to actually run the application using the bean is:

  • the html file which references the applet class file
  • the extracted ReportViewerBean.jar file and any supporting jar files
  • the applet class file.


Programming the Embeddable Crystal Reports Designer Control

This section demonstrates how to integrate the Embeddable Crystal Reports Designer Control (Embeddable Designer) into your application. Included are tutorials on creating sample applications in both Microsoft Visual Basic and Microsoft Visual C++. A brief section on creating reports in the designer at runtime is also included.

Click the appropriate link to jump to that section:

  • Overview
  • Creating a Microsoft Visual Basic sample application with the Embeddable Designer
  • Creating a Microsoft Visual C++ sample application with the Embeddable Designer
  • Designing reports in the Embeddable Designer


Overview

The Embeddable Crystal Reports Designer Control (Embeddable Designer) is a new addition to the Report Designer Component. Easily integrated into your application, the Embeddable Designer provides your users with an interactive environment to design or edit Crystal Reports.

The following examples demonstrate how to create a sample application using the Embeddable Designer in both Microsoft Visual Basic and Microsoft Visual C++. Two tutorials are provided:

  • Creating a Microsoft Visual Basic sample application with the Embeddable Designer
  • Creating a Microsoft Visual C++ sample application with the Embeddable Designer


Creating a Microsoft Visual Basic sample application with the Embeddable Designer

This tutorial assumes that you have prior knowledge of Microsoft Visual Basic, Crystal Reports, and the Report Designer Component. The following procedure and sample code detail how to create an application that demonstrates the Embeddable Designer. The application will consist of a single form with a tab control and buttons to create a new report or open an existing report. The tab control has two property pages. The first page (Designer tab) contains the Embeddable Designer, and the second page (Viewer tab) contains the Crystal Reports Viewer Control. See Programming the Crystal Report Viewers. With the application running, you will be able to open a new report or an existing report in the Embeddable Designer. After designing or editing a report, view it in the Crystal Report Viewer. When you go back to the Embeddable Designer to make changes, you'll see those changes updated automatically in the Crystal Report Viewer.

Note: The sample application was created in Microsoft Visual Basic version 6.0 with Service Pack 4.

This tutorial contains the following steps:

  • Step 1: Creating the user interface (Microsoft Visual Basic)
  • Step 2: Writing the code (Microsoft Visual Basic)
  • Step 3: Running the Embeddable Designer application (Microsoft Visual Basic).


Step 1: Creating the user interface (Microsoft Visual Basic)

To return to the introduction, go to Creating a Microsoft Visual Basic sample application with the Embeddable Designer.

In this step, you will add the references, components, forms, and controls for the application.

  1. Create a new Standard EXE project.
  2. Add the following components to the project:
      • Crystal Reports Viewer Control
      • Embeddable Crystal Reports 8.5 Designer Control
      • Microsoft Common Dialog 6.0
      • Microsoft Tabbed Dialog Control 6.0 (Sp4).
  3. Add the following reference to the project:
      • Crystal Reports 8.5 ActiveX Designer Design and Runtime Library.

        Note: See Programming the Crystal Report Viewers for more information.

  4. Add the following controls from the Toolbox to the form:
      • three CommandButton controls
      • Common Dialog (Microsoft Common Dialog Control 6.0)
      • SSTab1 (Microsoft Tabbed Dialog Control 6.0 (SP4))
      • CRDesignerCtrl (Embeddable Crystal Reports 8.5 Designer Control)
      • CRViewer (Crystal Report Viewer Control).
  5. Set the properties for the form and the controls:
      • Form1 (Main form for the application):
            • Name = frmMain
            • Caption = Embeddable Crystal Reports 8.5 Designer Control Sample
            • Height = 8265
            • Width = 10815
      • SStab (Tabbed control containing the Embeddable Designer and Report Viewer controls):

        Note: Click the tabs on SSTab1 to access the separate Caption properties.

            • Name = SSTab1
            • Tabs = 2
            • Tab1 Caption = Design
            • Tab2 Caption = Preview
            • Enabled = False
            • Height = 7600
            • Left = 0
            • Tab Height = 300
            • Top = 130
            • Width = 10825
      • CRDesignerCtrl1 (Designs and edits reports):

        Note: Place the control on the tab labeled "Designer."

            • Name = CRDesignerCtrl1
            • Height = 6540
            • Left = 0
            • Top = 0
            • Width = 10325
      • CRViewer (Views reports):
            • Name = CRViewer1
            • Height = 10340
            • Left = 120
            • Top = 360
            • Height = 6600
      • CommonDialog (Creates an Open dialog to select reports):
            • Name = CommonDialog1
            • Filter = Crystal Reports |*.rpt
      • Button1 (Creates a new report):
            • Name = cmdNewReport
            • Caption = &New Report
            • Left = 120
            • Top = 7850
      • Button2 (Opens an existing report):
            • Name = cmdOpenReport
            • Caption = &OpenReport
            • Left = 1950
            • Top = 7850
      • Button3 (Closes the form and exits the application):
            • Name = cmdExit
            • Caption = E&xit
            • Left = 9030
            • Top = 7850

To continue with this procedure, go to Step 2: Writing the code (Microsoft Visual Basic).


Step 2: Writing the code (Microsoft Visual Basic)

To return to the previous part of this procedure, go to Step 1: Creating the user interface (Microsoft Visual Basic).


Embeddable_Designer_Programming6.html

In this step you will add the code to:

  • create a new report
  • create an Open dialog box to open an existing report
  • set the report object to CRDesignerCtrl1 and view the report in design mode
  • set the report object to CRViewer1, set the zoom level, and view the report
  • refresh the report when switching from the Designer tab to the Viewer tab on the Microsoft Tabbed Dialog Control.
  1. Type or insert the sample code below into the code module of frmMain.
  2. Once you have added the code, on the Run menu click Start to run the application.

Note: Error handling is not included in the code samples.

Option Explicit

Dim m_Application As New CRAXDDRT.Application
Dim m_Report As CRAXDDRT.Report

' *************************************************************
'DisplayReport is a procedure that
' - Enables the Tab control the first time a report is created
'   or opened.
' - Sets the report object to the Embeddable Designer(CRDesigner1).
' - Disables the Help menu in the Embeddable Designer.
' - Sets the report object to the Crystal Report Viewer Control
'   (CRViewer1).
' - Sets the Crystal Reports Viewer to view the report.
'
Public Sub DisplayReport()
' Enable the tab control if disabled.
If SSTab1.Enabled = False Then SSTab1.Enabled = True

' Set the Report Object
CRDesignerCtrl1.ReportObject = m_Report

' Note----------------
' Set all other properties for CRDesignerCtrl1 after setting the
' ReportObject property
' --------------------

' Disable the Help menu
CRDesignerCtrl1.EnableHelp = False

' Set the report source
CRViewer1.ReportSource = m_Report

' Set the viewer to view the report
CRViewer1.ViewReport
' Set the zoom level to fit the page
' to the width of the viewer window
CRViewer1.Zoom 1
End Sub

' *************************************************************
Private Sub Form_Load()
'Set the tab control to display the Designer tab
'when the form is loaded
SSTab1.Tab = 0
End Sub

' *************************************************************
Private Sub SSTab1_Click(PreviousTab As Integer)
' Refresh the report when clicking Preview,
' without refreshing the data from the server.
If PreviousTab = 0 Then CRViewer1.RefreshEx False

End Sub

' *************************************************************
' Create a new report and display it in the Embeddable Designer
'
Private Sub cmdNew_Click()
' Set the report object to nothing
Set m_Report = Nothing

' Create a new report
Set m_Report = m_Application.NewReport

' Call DisplayReport to set the report to the Embeddable Designer
' and the Crystal Report Viewer and then display the report in the
' Embeddable Designer.
Call DisplayReport
End Sub

' *************************************************************
' Use the Microsoft Common Dialog control to open a report.
'
Private Sub cmdOpen_Click()

CommonDialog1.CancelError = True

On Error GoTo errHandler

' Display the open dialog box
CommonDialog1.ShowOpen

' Set the report object to nothing
Set m_Report = Nothing

' Open the selected report
Set m_Report = m_Application.OpenReport(CommonDialog1.FileName, 1)

' Call DisplayReport to set the report to the Embeddable Designer
' and the Crystal Report Viewer
Call DisplayReport

Exit Sub

errHandler:
'User cancelled dialog
End Sub

' *************************************************************
Private Sub cmdAbout_Click()
frmAbout.Show vbModal
End Sub

' *************************************************************
Private Sub cmdExit_Click()
Unload Me
End Sub

To continue with this procedure, go to Step 3: Running the Embeddable Designer application (Microsoft Visual Basic).


Step 3: Running the Embeddable Designer application (Microsoft Visual Basic)

To return to the previous part of this procedure, go to Step 2: Writing the code (Microsoft Visual Basic).

In this step you will:

  • create and design a new report in the Embeddable Designer
  • view the report and any changes made to the report
  • open and edit an existing report in the Embeddable Designer
  • view the report and any changes made to the report.
  1. With the application running, click New Report.

    An empty report will appear in the Embeddable Designer.

    Note: The interface for the Embeddable Designer is the same one used for ActiveX Designer reports created in the Microsoft Visual Basic IDE with the Crystal Reports Report Designer Component.

  2. Design a new report to view.

    If you are not familiar with the designer environment, see Designing reports in the Embeddable Designer for a step-by-step procedure on creating a simple report off the Xtreme Sample Database ODBC data source.

  3. Click Preview to view the report in the Crystal Report Viewer.
  4. Click Design and make some changes to the report. Then click Preview to see the changes in the Crystal Report Viewer.
  5. Click Open.
  6. In the Open dialog box select one of the sample reports and click Open to view the report in the Embeddable Designer.
  7. Click Preview to view the report in the Crystal Report Viewer.
  8. Click Design and make some changes to the report. Then click Preview to see the changes in the Crystal Report Viewer.

To return to the introduction, go to Creating a Microsoft Visual Basic sample application with the Embeddable Designer.


Creating a Microsoft Visual C++ sample application with the Embeddable Designer

This tutorial assumes that you have prior knowledge of Microsoft Visual C++, Crystal Reports, and the Report Designer Component. The following procedure and sample code create an application that demonstrates the Embeddable Designer. The application will consist of a main dialogs for the Embeddable Designer, and for the Crystal Reports Viewer Control. For details, see Programming the Crystal Report Viewers.

With the application running, you will be able to open a new or existing report in the Embeddable Designer. After designing or editing a report, you can preview it in the Crystal Report Viewer by clicking the Preview button. You can then return to the Embeddable Designer by clicking the Design button. When you go back to to edit the report, you can see those changes updated automatically by clicking the Preview button again.

This tutorial contains the following steps:

  • Step 1: Creating the User Interface (Microsoft Visual C++)
  • Step 2: Adding member variables and member functions (Microsoft Visual C++)
  • Step 3: Writing the code (Microsoft Visual C++)
  • Step 4: Running the Embeddable Designer application (Microsoft Visual C++).


Step 1: Creating the User Interface (Microsoft Visual C++)

To return to the introduction, go to Creating a Microsoft Visual C++ sample application with the Embeddable Designer.

In this step, you will create a Dialog-based MFC.EXE application and add the components, and controls for the application.

  1. Using the AppWizard, create a starter Dialog-based MFC application. The main dialog will display reports in Embeddable Designer and the Crystal Report Viewer.
      • Project Name: Embeddable_Designer
      • Application Class Name: CEmbeddable_DesignerApp
      • Dialog Class Name: CEmbeddable_DesignerDlg
  2. Add the Embeddable Designer Control and the Crystal Report Viewer Control through the Components and Controls Gallery dialog box. The controls are in the Registered ActiveX Controls folder:
      • Embeddable Crystal Reports 8.5 Designer Control
      • Crystal Report Viewer Control
  3. Add the following controls from the Toolbox to IDD_EMBEDDABLE_DESIGNER_DIALOG (Embeddable Designer dialog):
        • six buttons
        • Embeddable Crystal Reports 8.5 Designer
        • Crystal Report Viewer
  4. Set the properties for the Embeddable Designer dialog and its controls:
      • IDD_EMBEDDABLE_DESIGNER_DIALOG (Create, open, save, design and preview reports):
            • Caption: Embeddable Designer
            • Height: 340
            • Width: 540
      • Embeddable Crystal Reports 8.5 Designer Control (Designs and edits reports):
            • Height: 300
            • Left: 7
            • Top: 7
            • Width: 525
      • Crystal Report Viewer:
            • Height: 300
            • Left: 7
            • Top: 7
            • Width: 525

Note: Either the Embeddable Designer or the Crystal Report Viewer will be hidden depending on wether the user is designing or previewing a report.

    • All Buttons (Common Properties):
          • Align all Buttons to the bottom of the form
          • Height: 14
          • Width: 50
    • Button1 (Creates a new report):
          • ID: IDC_NEW_REPORT
          • Caption: &New Report
          • Left: 7
    • Button2 (Opens an existing report):
          • ID: IDC_OPEN_REPORT
          • Caption: &Open Report
          • Left: 66
    • Button3 (Saves a report):
          • ID: IDC_SAVE_REPORT
          • Caption: &Save Report
          • Left: 125
    • Button4 (Shows the Crystal Report Viewer and hides the Embeddable Designer.):
          • ID: IDC_PREVIEW
          • Caption: &Preview
          • Left: 184
    • Button5 (Shows the Embeddable Designer and hides the Crystal Report Viewer):
          • ID: IDC_SHOW_DESIGNER
          • Caption: &Design
          • Left: 184
    • Button6 (Exits the application):
          • ID: IDCANCEL
          • Caption: E&xit
          • Left: 483

To continue with this procedure, go to Step 2: Adding member variables and member functions (Microsoft Visual C++).


Step 2: Adding member variables and member functions (Microsoft Visual C++)

To return to the previous part of this procedure, go to Step 1: Creating the User Interface (Microsoft Visual C++).

In this step, you will add the member variables for the controls on the Embeddable Designer dialog and then add member functions, and member variables for the CEmbeddable_DesignerDlg class.

This step is broken into 2 sections:

  • Adding member variables for the Embeddable Designer dialog controls
  • Adding member variables and functions to the CEmbeddable_Designer class


Adding member variables for the Embeddable Designer
dialog controls

To return to the previous part of this procedure, go to Step 2: Adding member variables and member functions (Microsoft Visual C++).

Use the Class Wizard to create the member variables for the controls.

  1. Create member variables for the controls on the Embeddable Designer dialog:
      • Embeddable Designer Control:
            • Control ID: IDC_EMBEDDABLECRYSTALREPORTSDESIGNERCTRL
            • Type: CCRDesignerCtrl
            • Member: m_Designer
      • Crystal Report Viewer Control:
            • Control ID: IDC_CRVIEWER1
            • Type: CCrystalReportViewer4
            • Member: m_Viewer
      • New Report Button:
            • Control ID: IDC_NEW_REPORT
            • Type: CButton
            • Member: m_NewReport
      • Open Report Button:
            • Control ID: IDC_OPEN_REPORT
            • Type: CButton
            • Member: m_OpenReport
      • Save Report Button:
            • Control ID: IDC_SAVE_REPORT
            • Type: CButton
            • Member: m_SaveReport
      • Preview Button:
            • Control ID: IDC_PREVIEW
            • Type: CButton
            • Member: m_Preview
      • Design Button:
            • Control ID: IDC_SHOW_DESIGNER
            • Type: CButton
            • Member: m_ShowDesigner

Adding member variables and functions to the CEmbeddable_Designer class.


Adding member variables and functions
to the CEmbeddable_Designer class

To return to the previous part of this procedure, go to Adding member variables for the Embeddable Designer dialog controls.

Add the following member variables, and member functions to the CEmbeddable_Designer class. The code for the functions will be added in Step 3: Writing the code (Microsoft Visual C++).

  1. Create the following member variables.
      • Application pointer for the Craxddrt Application Object:
            • Variable Type: IApplicationPtr
            • Variable Name: m_Application
      • Report pointer for the Craxddrt Report Object:
            • Variable Type: IReportPtr
            • Variable Name: m_Report
  2. Create the following member function:
      • Function to create or open a report and initialize the controls on the Embeddable Designer form.
            • Function Type: void
            • Function Declaration: InitReport(BOOL bNew)
  3. Add a member function for the BN_CLICKED message of each of the following buttons:
      • New Report: (Click to create a new report)
            • Member function name: OnNewReport
      • Open Report: (Click to open an existing report)
            • Member function name: OnOpenReport
      • Save Report: (Click to save the current report)
            • Member function name: OnSaveReport
      • Preview: (Click to Preview the current report)
            • Member function name: OnPreview
      • Design: (Click to edit the current report)
            • Member function name: OnShowDesigner

To continue with this procedure, go to Step 3: Writing the code (Microsoft Visual C++).


Step 3: Writing the code (Microsoft Visual C++)

To return to the previous part of this procedure, go to Step 2: Adding member variables and member functions (Microsoft Visual C++).

In this step, you will write the code for member functions added in Step 2: Adding member variables and member functions (Microsoft Visual C++); you will also add directives and constants to the source and header files.

This step is broken into 2 sections:

  • Adding directives and constants to the source and header files
  • Adding the code for the CEmbeddable_Designer class


Adding directives and constants to the source and header files

To return to the previous part of this procedure, go to Step 2: Adding member variables and member functions (Microsoft Visual C++).

Add the following directives and constants to the Source and Header files.

  1. Add a constant to Embeddable_DesignerDlg.cpp.

// Filter for the Open dialog box and the Save As dialog box

static const char BASED_CODE szFilter[] = "Crystal Reports|*.rpt||";// Filter for the Open dialog box and the Save As dialog box

static const char BASED_CODE szFilter[] = "Crystal Reports|*.rpt||";
  2. Add the directive to Embeddable_Designer.h

//Import the Crystal Reports 8.5 ActiveX Designer Design and Runtime Library

#import "craxddrt.tlb" no_namespace//Import the Crystal Reports 8.5 ActiveX Designer Design and Runtime Library

#import "craxddrt.tlb" no_namespace

Note: Copy Craxddrt.tlb to your application directory. Craxddrt.tlb can be found in the \Crystal Reports\Developer Files\include path, off the directory you installed Crystal Reports to.

To continue with this procedure, go to Adding the code for the CEmbeddable_Designer class.


Adding the code for the CEmbeddable_Designer class

To return to the previous part of this procedure, go to Adding directives and constants to the source and header files.

Type or insert the code for the member functions created in Adding member variables and functions to the CEmbeddable_Designer class. The CEmbeddable_DesignerDlg class handles the basic functionality of the Embeddable Designer sample application. The class will handle all of the report functionality including creating a new report or opening an existing report, and displaying it in the Embeddable Designer or the Crystal Report Viewer. Once a report is designed or edited it can be saved, previewed, or refreshed.

Note: Error handling is not included in the code samples.

  1. Add the code to the OnInitDialog function.

 // Hide the Crystal Reports Viewer control and show the
    // Embeddable Designer oontrol.
    m_Viewer.ShowWindow(SW_HIDE);

m_Designer.ShowWindow(SW_SHOW); // Hide the Crystal Reports Viewer control and show the

// Embeddable Designer oontrol.

m_Viewer.ShowWindow(SW_HIDE);

m_Designer.ShowWindow(SW_SHOW);
  2. Add the code for the InitReport function.

// In this function a report is created or opened. The report is set to
// the Embeddable Designer and Crystal Report Viewer, with the Embeddable
// Designer visible and the Crystal Report Viewer hidden. Then the
// command buttons are initialized so that Save Report, and Preview are
// enabled, and Design is disabled and hidden.
void CEmbeddable_DesignerDlg::InitReport(BOOL bNew)
{
    // Create a new report for designing and previewing.
    if(bNew)
    {
        m_Application.CreateInstance("CrystalDesignRuntime.Application");
        m_Report = m_Application->NewReport();
    }

    // Show an Open dialog box, and then browse and open a report
    // for editing and previewing.
    else
    }
        // Initialize the Open dialog box to only display the
        // Crystal Report(.rpt) file type.
        CFileDialog FileDlg(TRUE,"*.rpt",NULL, OFN_EXPLORER, szFilter);

        // Show the Open dialog box
        int iReturn = FileDlg.DoModal();

        if(iReturn == IDOK)
        {
            // Get the name and path of the report file selected from the
            // Open dialog box.
            _bstr_t FileName(FileDlg.GetPathName().AllocSysString());

            // Create the Application Object.

m_Application.CreateInstance("CrystalDesignRuntime.Application");

            // Open the report selected from the Open dialog box.
            m_Report = m_Application->OpenReport(FileName);
        }
        else if (iReturn = IDCANCEL)
        {
            // Terminate the execution of the function if the
            // user cancels.
            return;
        }
    }

    // Set the report object to the Embeddable Designer.
    m_Designer.SetReportObject(m_Report);

    // Set the report souce for the Crystal Reports Viewer
    m_Viewer.SetReportSource(m_Report);

    // Set the width of the report page to the width of the viewing area
    m_Viewer.Zoom(1);

    // View the report in the Crystal Reports Viewer control.
    m_Viewer.ViewReport();

    // Check if the Save Report button is enabled.
    // If the button is disabled then enable the Save Report,
    // and Preview buttons. The Save Report button will always
    // be enabled once the first report is opened or created.
    BOOL bEnabled;
    bEnabled = m_DesignerSettings.IsWindowEnabled();

    if( bEnabled == FALSE)
    {
        m_SaveReport.EnableWindow(TRUE);
        m_Preview.EnableWindow(TRUE);
    }

    // Check if the Embeddable Designer is hidden.
    // If it is hidden then hide the Design button, show the
    // Preview button, hide the Crystal Reports Viewer, and
    // show the Embeddable Designer.
    if(!m_Designer.IsWindowVisible())
    {
        m_ShowDesigner.ShowWindow(SW_HIDE);
        m_Preview.ShowWindow(SW_SHOW);
        m_Viewer.ShowWindow(FALSE);
        m_Designer.ShowWindow(TRUE);
    }

}// In this function a report is created or opened. The report is set to

// the Embeddable Designer and Crystal Report Viewer, with the Embeddable

// Designer visible and the Crystal Report Viewer hidden. Then the

// command buttons are initialized so that Save Report, and Preview are

// enabled, and Design is disabled and hidden.

void CEmbeddable_DesignerDlg::InitReport(BOOL bNew)

{

// Create a new report for designing and previewing.

if(bNew)

{

m_Application.CreateInstance("CrystalDesignRuntime.Application");

m_Report = m_Application->NewReport();

}

// Show an Open dialog box, and then browse and open a report

// for editing and previewing.

else

}

// Initialize the Open dialog box to only display the

// Crystal Report(.rpt) file type.

CFileDialog FileDlg(TRUE,"*.rpt",NULL, OFN_EXPLORER, szFilter);

// Show the Open dialog box

int iReturn = FileDlg.DoModal();

if(iReturn == IDOK)

{

// Get the name and path of the report file selected from the

// Open dialog box.

_bstr_t FileName(FileDlg.GetPathName().AllocSysString());

// Create the Application Object.

m_Application.CreateInstance("CrystalDesignRuntime.Application");

// Open the report selected from the Open dialog box.

m_Report = m_Application->OpenReport(FileName);

}

else if (iReturn = IDCANCEL)

{

// Terminate the execution of the function if the

// user cancels.

return;

}

}

// Set the report object to the Embeddable Designer.

m_Designer.SetReportObject(m_Report);

// Set the report souce for the Crystal Reports Viewer

m_Viewer.SetReportSource(m_Report);

// Set the width of the report page to the width of the viewing area

m_Viewer.Zoom(1);

// View the report in the Crystal Reports Viewer control.

m_Viewer.ViewReport();

// Check if the Save Report button is enabled.

// If the button is disabled then enable the Save Report,

// and Preview buttons. The Save Report button will always

// be enabled once the first report is opened or created.

BOOL bEnabled;

bEnabled = m_DesignerSettings.IsWindowEnabled();

if( bEnabled == FALSE)

{

m_SaveReport.EnableWindow(TRUE);

m_Preview.EnableWindow(TRUE);

}

// Check if the Embeddable Designer is hidden.

// If it is hidden then hide the Design button, show the

// Preview button, hide the Crystal Reports Viewer, and

// show the Embeddable Designer.

if(!m_Designer.IsWindowVisible())

{

m_ShowDesigner.ShowWindow(SW_HIDE);

m_Preview.ShowWindow(SW_SHOW);

m_Viewer.ShowWindow(FALSE);

m_Designer.ShowWindow(TRUE);

}

}

  3. Add the code for the OnNewReport function.

// In this function call the InitReport function and pass a
// value of True to create a new report. Passing a value of
// False opens an existing report.
void CEmbeddable_DesignerDlg::OnNewReport()
{
    InitReport(TRUE);

}// In this function call the InitReport function and pass a

// value of True to create a new report. Passing a value of

// False opens an existing report.

void CEmbeddable_DesignerDlg::OnNewReport()

{

InitReport(TRUE);

}

  4. Add the code for the OnOpenReport function.

// In this function call the InitReport function and pass
// a value of False to open an existing report. Passing a
// value of True creates a new report.
void CEmbeddable_DesignerDlg::OnOpenReport()
{
    InitReport(FALSE);

}// In this function call the InitReport function and pass

// a value of False to open an existing report. Passing a

// value of True creates a new report.

void CEmbeddable_DesignerDlg::OnOpenReport()

{

InitReport(FALSE);

}
  5. Add the code for the OnSaveReport function.

// In this function open a Save As dialog box and save the current
// report to the selected path and name.
void CEmbeddable_DesignerDlg::OnSaveReport()
{

    // Initialize the Save As dialog box to only display the Crystal
    // Report (.rpt) file type.
    CFileDialog FileDlg(FALSE,"*.rpt",NULL,OFN_EXPLORER, szFilter);

    // Show the Save As dialog box.
    int iReturn = FileDlg.DoModal();

    if(iReturn == IDOK)
    {
        // Get the path and name selected in the Save As dialog box.
        _bstr_t FileName(FileDlg.GetPathName().AllocSysString());

        // Save the report to the path and name specified in the
        // Save As dialog box.
        m_Designer.SaveReport(FileName);
    }
    else if(iReturn == IDCANCEL)
    {
        // Terminate the execution of the function if the
        // user cancels.
        return;
    }

}// In this function open a Save As dialog box and save the current

// report to the selected path and name.

void CEmbeddable_DesignerDlg::OnSaveReport()

{

// Initialize the Save As dialog box to only display the Crystal

// Report (.rpt) file type.

CFileDialog FileDlg(FALSE,"*.rpt",NULL,OFN_EXPLORER, szFilter);

// Show the Save As dialog box.

int iReturn = FileDlg.DoModal();

if(iReturn == IDOK)

{

// Get the path and name selected in the Save As dialog box.

_bstr_t FileName(FileDlg.GetPathName().AllocSysString());

// Save the report to the path and name specified in the

// Save As dialog box.

m_Designer.SaveReport(FileName);

}

else if(iReturn == IDCANCEL)

{

// Terminate the execution of the function if the

// user cancels.

return;

}

}
  6. Add the code for the OnPreview function

// In this function, refresh the report without refreshing the data
// source, hide the Preview button and the Embeddable Designer, and
// then show the Design button and the Crystal Report Viewer.
void CEmbeddable_DesignerDlg::OnPreview()
{
    m_Viewer.RefreshEx(FALSE);
    m_Preview.ShowWindow(SW_HIDE);
    m_Designer.ShowWindow(SW_HIDE);
    m_ShowDesigner.ShowWindow(SW_SHOW);
    m_Viewer.ShowWindow(SW_SHOW);

}// In this function, refresh the report without refreshing the data

// source, hide the Preview button and the Embeddable Designer, and

// then show the Design button and the Crystal Report Viewer.

void CEmbeddable_DesignerDlg::OnPreview()

{

m_Viewer.RefreshEx(FALSE);

m_Preview.ShowWindow(SW_HIDE);

m_Designer.ShowWindow(SW_HIDE);

m_ShowDesigner.ShowWindow(SW_SHOW);

m_Viewer.ShowWindow(SW_SHOW);

}
  7. Add the code for the OnShowDesigner function.

// In this function, hide the Design button and the Crystal Report

// Viewer, and show the Preview button and the Embeddable Designer.

void CEmbeddable_DesignerDlg::OnShowDesigner()

{

m_ShowDesigner.ShowWindow(SW_HIDE);

m_Viewer.ShowWindow(SW_HIDE);

m_Preview.ShowWindow(SW_SHOW);

m_Designer.ShowWindow(SW_SHOW);

}

// In this function, hide the Design button and the Crystal Report

// Viewer, and show the Preview button and the Embeddable Designer.

void CEmbeddable_DesignerDlg::OnShowDesigner()

{

m_ShowDesigner.ShowWindow(SW_HIDE);

m_Viewer.ShowWindow(SW_HIDE);

m_Preview.ShowWindow(SW_SHOW);

m_Designer.ShowWindow(SW_SHOW);

}

To continue with this procedure, go to Step 4: Running the Embeddable Designer application (Microsoft Visual C++).


Step 4: Running the Embeddable Designer application (Microsoft Visual C++)

To return to the previous part of this procedure, go to Step 3: Writing the code (Microsoft Visual C++).

In this step you will:

  • create and design a new report in the Embeddable Designer
  • view the report and any changes made to the report
  • open and edit an existing report in the Embeddable Designer
  • view the report and any changes made to the report
  • save a report.
  1. With the application running, click New Report.

    An empty report will appear in the Embeddable Designer.

    Note: The interface for the Embeddable Designer is the same one used for ActiveX Designer reports created in the Microsoft Visual Basic IDE with the Report Designer Component.

  2. Design a new report to view.

    If you are not familiar with the designer environment, refer to Designing reports in the Embeddable Designer for a step-by-step procedure on creating a simple report off the Xtreme Sample Database ODBC data source.

  3. Click Preview to view the report in the Crystal Report Viewer.
  4. Click Design and make some changes to the report in the Embeddable Designer. Then click Preview to see the changes in the Crystal Report Viewer .
  5. Click Open. In the Open dialog box, select one of the sample reports and click Open to view the report in the Embeddable Designer dialog.
  6. Click Preview to view the report in the Crystal Report Viewer.
  7. Click Design and make some changes to the report in the Embeddable Designer. Then click Preview to see the changes in the Crystal Report Viewer .
  8. Click Save Report.
  9. In the Save As dialog box, browse to the desired directory, type the name you want to save the report as, and then click Save.

Note: When you are designing a report the Preview button will be visible, and when you are previewing a report the Design button will be visible.

To return to the introduction, go to Creating a Microsoft Visual C++ sample application with the Embeddable Designer.


Designing reports in the Embeddable Designer

Designing reports in the Embeddable Designer is an easy, intuitive process. In this procedure, you will create a simple report off the Xtreme Sample Database ODBC data source, which installs with Crystal Reports. The report will include a text object, database fields, and a group.

The procedure contains the following steps:

    • Step 1: Adding a data source to the report
    • Step 2: Adding fields and grouping to the report


Step 1: Adding a data source to the report

In this step, you will use the Data Explorer to add the Customer table from the ODBC data source Xtreme Sample Database.

  1. On the Main Report tab, right-click Database Fields, and then click Add Database to Report.
  2. In the Data Explorer dialog box, expand ODBC and expand Xtreme Sample Database; then select Customer, click Add, and click Close.
  3. In the Visual Linking Expert dialog box, click OK.

    The data source is now added to the report.


Step 2: Adding fields and grouping to the report

In this step you will add a text object to the Report Header section, the Customer Name and Last Year's Sales Fields to the Details section, and a group based on the Region field.

  1. On the Main Report tab, right-click in the white space to access the shortcut menu.
  2. On the shortcut menu, point to Insert, and then click Text Object.

    An object frame appears with the Arrow pointer.

  3. Drag the object frame to the Report Header section and click to release the text object.
  4. Double-click the text object to edit it, and then type: Xtreme Sales Report by Region.
  5. Expand Database Fields, and then expand Customer to view the database fields.
  6. Drag the Customer Name and Last Year's Sales fields into the Details section.

    A column heading for each field is automatically placed in the Page Header section.

  7. Click Insert Group on the toolbar.
  8. In the Insert Group dialog box, select Region, and then click OK.

You are now ready to preview, export, print, or save the report. See Crystal Reports Online Help (crw.chm) for more information on designing reports in the Crystal Reports environment.

Note: You can find the typical Crystal Report Designer commands (menu items and toolbar buttons) on the shortcut menu of the Embeddable Designer. The Embeddable Designer does not support the Chart Analyzer, Olap Grids, or Maps.


Working with Visual C++ and
Visual InterDev

This section illustrates how the Report Designer Component (RDC) can be integrated using other development languages. Included are examples in Visual C++ and Visual Interdev.

Click the appropriate link to jump to that section:

  • Overview
  • Using the RDC with Visual C++
  • Using the RDC with Visual InterDev


Overview

While much of this help system is aimed at the Visual Basic developer, it is important to note that the integration methods can be used in any environment that supports COM. This section shows you how to use different integration methods with other popular development environments.

Note: Visit the Seagate Software Developer Zone web site at
http://www.seagatesoftware.com/products/dev_zone
Click Support to get links for finding documentation and knowledge base articles about the Report Designer Component.


Using the RDC with Visual C++

There are different ways to access the Report Designer Component (RDC) and any other COM Automation server through Visual C++. This section describes how to use the #import method.

Manipulating the RDC in Microsoft Visual C++ involves three steps:

  • Define and instantiate a variable to be used to manipulate the RDC COM object.
  • Instantiate an actual instance of the RDC COM object and assign it to a variable.
  • Manipulate the Properties and Methods and then output the report.

The following section leads you through the details in each of these steps.

Printing a Report through Visual C++

To print a report through Visual C++
  1. Open Visual C++ 6.0 if it isn't already running.
  2. From the File menu, select New. In the New dialog box select the MFC AppWizard (exe) from the Projects tab. Type in MyRDC for the Project Name and click OK.
  3. Click the Finish button to accept the defaults for the MFC AppWizard and then click OK in the New Project Information dialog box.
  4. Add a reference to the RDC runtime object Model. From the File|Open menu select the StdAfx.h file that was generated by the MFC App wizard and Click Open. Add the following line after the #include directives:
#import "C:\Program Files\Seagate Software\Crystal Reports\Developer
Files\include\craxdrt.tlb"

Note: This is the default location of the RDC runtime object model (craxdrt.dll).

  5. Before you can invoke an RDC object, you must initialize OLE. From the File|Open menu, open the MyRDC.CPP file and add the following code:
struct InitOle {
InitOle()  { ::CoInitialize(NULL); }
~InitOle() { ::CoUninitialize();   }
} _init_InitOle_;
  6. For optional Variant parameters declare a dummy variable in the MyRDC2.CPP class.
Variant dummy;
  7. Add the following constants in the declaration's of the MyRDC2.CPP class:
// The constants needed to create the Application and Report Objects COM
objects
const CLSID CLSID_Application =
{0xb4741fd0,0x45a6,0x11d1,{0xab,0xec,0x00,0xa0,0xc9,0x27,0x4b,0x91}};
const IID IID_IApplication =
{0x0bac5cf2,0x44c9,0x11d1,{0xab,0xec,0x00,0xa0,0xc9,0x27,0x4b,0x91}};
const CLSID CLSID_ReportObjects =
{0xb4741e60,0x45a6,0x11d1,{0xab,0xec,0x00,0xa0,0xc9,0x27,0x4b,0x91}};
const IID IID_IReportObjects =
{0x0bac59b2,0x44c9,0x11d1,{0xab,0xec,0x00,0xa0,0xc9,0x27,0x4b,0x91}};

Opening and Printing a Crystal Report through the RDC

To open and print a Crystal Report through the RDC
  1. From the File|Open menu open the MyRDC.CPP file. Add the following code to the MyRDC.InitInstance() method just before the return statement:
// A dummy variant
VariantInit (&dummy);
dummy.vt = VT_EMPTY;
HRESULT                hr = S_OK;
            IApplicationPtr m_Application = NULL;
            IReportPtr m_Report = NULL;

            // Specify the path to the report you want to print
_bstr_t ReportPath("c:\\Program Files\\Seagate Software\\Crystal
Reports\\Samples\\En\\Reports\\General Business\\Inventory.rpt");
_variant_t vtEmpty(DISP_E_PARAMNOTFOUND, VT_ERROR);
// Instantiate the IApplication object
hr = CoCreateInstance(CLSID_Application, NULL, CLSCTX_INPROC_SERVER ,
IID_IApplication, (void **) & CRAXDRT::IApplication);
//Open the Report using the OpenReport method
m_Report = m_Application->OpenReport(ReportPath, dummy)
//Print the Report to printer
m_Report->PrintOut(dummy, dummy, dummy, dummy

);
  2. Finally, from the Build menu, select Rebuild All.

There are hundreds of properties, methods, and events in the Report Designer Component object model that you can manipulate through your code to meet the demands of virtually any reporting requirement.


Using the RDC with Visual InterDev

The following topics are directed at the developer of Web applications using the Report Integration Controls.

Installation

When you install Crystal Reports, the Report Integration Controls are installed in the folder SEAGATE SOFTWARE\SHARED\DESIGN TIME CONTROL by default. Initially, to set up the Report Integration Controls as Design Time Controls (DTC's) for use in Visual InterDev 6.0, you need to:

  1. Right-click in the Visual InterDev Toolbox. Choose Customize Toolbox from the shortcut menu.
  2. In the Customize Toolbox dialog box, select the Design Time Controls tab. Check the two items ReportSource and ReportViewer.

    The Report Integration Controls are comprised of the two DTC's, ReportSource and ReportViewer. You will find that these two DTC's are added to the Visual InterDev Toolbox. We will call them Report Source Control and Report Viewer Control below.


Adding Reports to the Current Project

You must first add a report to the current Visual InterDev project before you can apply any DTC's to it.

Insert a Report Source Control (DTC)

When you insert a Report Source Control into your Web application, you actually create an instance of the Report Source Control. Its name is ReportSourcei, where i is the i-th instance of the Report Source Control, i=1,2,3...

When you right-click on an instance of a Report Source Control, you will invoke the Report Source Properties dialog box.

The properties you can specify for an instance of a Report Source Control include the following:

Attach a report to the Report Source Control

General information: In the General tab of the Report Source Properties dialog box, you may attach a report to this instance of the Report Source Control from the list of reports included in the current project.

Logon and test connectivity

Logon information for database: In the Accounts tab of the Report Source Properties dialog box, you can specify the server and database names for each of the tables used in the attached report, and test connectivity for each of these servers after entering the logon information.

If the report is hosted on a Web Reports Server, you may leave the logon information blank, which will in turn prompt the end user to enter the logon information. If the report is hosted on an ASP server, then you must enter the logon information.

Specify how to handle parameters

Parameters: In the Parameters tab of the Report Source Properties dialog box, if the report is hosted on a Web Reports Server, you may specify whether to prompt the end user to choose from a default list of values, or enter a value for a parameter.

However, if the report is hosted on an ASP server, then you must choose a value for each input parameter.

Specify selection formulas

Selection formula: In the Formula tab of the Report Source Properties dialog box, you may specify your own selections formulas, or to modify existing selection formulas.


Insert a Report Viewer control (DTC)

When you insert a Report Viewer Control into your Web application, you create an instance of the Report Viewer Control. Its name is ReportVieweri, where i is the
i-th instance of the Report Viewer Control, i=1,2,3...

When you right-click on an instance of a Report Viewer Control, you will invoke the Report Viewer Properties dialog box.

Point the Viewer at the Report Source Control

The properties you can specify for an instance of a Report Viewer Control include:

General information: In the General tab of the Report Viewer Properties dialog box, you can select an instance of a Report Source Control and attach it to this instance of the Report Viewer Control. Upon clicking the Advanced button, you can specify a virtual path which is an alias to the directory of the Report Viewer Control.

Options for end users: In the Options tab of the Report Viewer Properties dialog box, you may specify the following for the end user:

  • the Report Viewer to use, whether it is the Report Viewer for Java or Report Viewer for ActiveX
  • the language to use for the Report Viewer, depending on the fonts installed on the current system
  • the size of the Report Viewer
  • the ability to refresh report in the Report Viewer
  • the ability to print report in the Report Viewer
  • the ability to export report from the Report Viewer
  • the ability to search in report in the Report Viewer
  • the ability to drill down in report in the Report Viewer
  • the ability to prompt on refresh of report in the Report Viewer
  • the ability to generate group tree in the Report Viewer
  • the ability to display group tree in the Report Viewer.

When you click OK, you're finished.


Report Designer Component Object Model

The Report Designer Component is the ultimate development tool for your reporting needs. In this section you will find a detailed description of the Report Designer Component Object Model and its properties, methods and events.

Click the appropriate link to jump to that section:

  • Overview of the Report Designer Object Model
  • Unification of the RDC object model
  • Object Naming Conflicts
  • Objects and Collections
  • Application Object
  • Area Object
  • Areas Collection
  • BlobFieldObject Object
  • CrossTabGroup Object
  • CrossTabGroups Collection
  • CrossTabObject Object
  • Database Object
  • DatabaseFieldDefinition Object
  • DatabaseFieldDefinitions Collection
  • DatabaseTable Object
  • DatabaseTables Collection
  • ExportOptions Object
  • FieldDefinitions Collection
  • FieldMappingData Object
  • FieldObject Object
  • FormattingInfo Object
  • FormulaFieldDefinition Object
  • GraphObject Object
  • GroupNameFieldDefinition Object
  • FieldDefinition Object
  • IReportObject
  • LineObject Object
  • MapObject Object
  • ObjectSummaryFieldDefinitions Collection
  • OlapGridObject Object
  • OleObject Object
  • Page Object
  • PageEngine Object
  • PageGenerator Object
  • Pages Collection
  • ParameterFieldDefinition Object
  • ParameterFieldDefinitions Collection
  • PrintingStatus Object
  • Report Object
  • ReportObjects Collection
  • RunningTotalFieldDefinition Object
  • RunningTotalFieldDefinitions Collection
  • Section Object
  • Sections Collection
  • SortField Object
  • SortFields Collection
  • SpecialVarFieldDefinition Object
  • SQLExpressionFieldDefinition Object
  • SQLExpressionFieldDefinitions Collection
  • SubreportLink Object
  • SubreportLinks Collection
  • SubreportObject Object
  • SummaryFieldDefinition Object
  • SummaryFieldDefinitions Collection
  • TableLink Object
  • TableLinks Collection
  • TextObject Object
  • Enumerated Types


Overview of the Report Designer Object Model

Please review the following comments regarding Object Naming Conflicts.


Unification of the RDC object model

Craxddrt.dll (Crystal Reports 8.5 ActiveX Designer Design and Runtime Library) is a new unified object model that combines the runtime capabilities of the Craxdrt.dll (Crystal Reports 8.5 ActiveX Designer Run Time Library) with the design time capabilities of the Craxddt.dll (Crystal Reports 8.5 ActiveX Designer Design Time Library). Craxddrt.dll will replace Craxddt.dll for versions 8.5 and up. Both the Craxddrt.dll and the Craxdrt.dll contain all the objects and associated methods, properties, and events needed for creating, opening, exporting, saving, and printing a report at run time. In addition, Craxddrt.dll is either used with the RDC ActiveX Designer when designing reports at design time, or used with the Embeddable Designer when designing reports at run time. See Embeddable Crystal Reports Designer Control Object Model for more information.

Note: The RDC ActiveX Designer is only available in Microsoft Visual Basic.

Prior to version 8.5, the Craxdrt.dll would be distributed with an application. Now the developer has a choice of two automation servers to distribute. Craxdrt.dll is backwards-compatible with previous versions and contains all the new features introduced in this version. Use the Craxdrt.dll for any client-side application that does not contain the Embeddable Designer, or use it for any server-side application. Craxddrt.dll is apartment-model threaded, but is not thread safe, and can only be used in a client-side application. Although the Craxddrt.dll is a fully functional automation server for the RDC, and can work in any client-side application, it will increase the install size. Therefore, it is recommended that you only use Craxddrt.dll with the Embeddable Crystal Reports Designer Control.


Object Naming Conflicts

If your project includes other libraries that contain objects named identical to those found in the Crystal Report Engine Object Library, you will encounter conflicts unless you reference the objects using a prefix. For example, if you have included the DAO Library with the Crystal Report Engine Object Library in your project, both libraries include a Database Object. In order to avoid conflicts, you must prefix the objects as follows:

CRAXDRT.Database

for the Crystal Report Engine Object Library, or

DAO.Database

for the DAO Library.


Objects and Collections

The following Objects and Collections, listed alphabetically, are discussed in this section. Properties, Methods and Events are listed under the appropriate Object or Collection.

Note: Some of the new report creation calls are not included in the free runtime license included with Crystal Reports. For a list of calls that require additional licensing, please see the Royalty help file (Royalty Required Runtime.hlp).


Application Object

An instance of the Application object can be created using the Visual Basic New keyword or the CreateObject function and the Prog Id CrystalRuntime.Application.[8]. For example:

  • Using the New keyword
Dim app as New CRAXDRT.Application

Set app = New CRAXDRT.Application

Or,

' Automatically creates a new instance of the object when it is first

' referenced in the code, so it doesn't have to be set.

Dim app as New Application
  • Using the CreateObject function
' If the version number of the application is not specified, CreateObject
will  ' create an application running against the new version of
craxdrt.dll
Dim app As Application

Set app = CreateObject("CrystalRuntime.Application")

Or,

' Specify the version number to require version 8 of the dll.
Dim app As Application

Set app = CreateObject("CrystalRuntime.Application.8")


Application Object Methods

The following methods are discussed in this section:

CanClose Method (Application Object)

GetVersion Method (Application Object)

LogOffServer Method (Application Object)

LogOnServer Method (Application Object)

LogOnServerEx Method (Application Object)

NewReport Method (Application Object)

OpenReport Method (Application Object)

SetMatchLogOnInfo Method (Application Object)

SetMorePrintEngineErrorMessages Method (Application Object)


CanClose Method (Application Object)

The CanClose method indicates whether or not the Application Object can be destroyed. This method will return FALSE as long as there are valid Report objects in existence and at least one Report Object is in the printing-in-progress state. The Application object can only be destroyed if no instances of the Report Object are in the printing-in-progress state. If you obtain a Report object directly from the Report Designer Component added to your project at design time, then CanClose will always return False until you destroy that object (usually by setting it equal to Nothing).

Syntax

Function CanClose () As Boolean

Returns
  • TRUE if the Engine can be closed.
  • FALSE if the Engine is busy.


GetVersion Method (Application Object)

The GetVersion method returns an integer that, when converted to hex, represents the version number of the dll.

Syntax

Function GetVersion () As Integer

Returns
  • Returns an integer that represents the version number of the dll when converted to hexidecimal.
Sample

'Display the version number in a text box.
Text1.text = Hex(CRXApplication.GetVersion)


LogOffServer Method (Application Object)

The LogOffServer method logs off an SQL server or other data sources such as ODBC or OleDB provider. Use this method when you have logged on to the data source using LogOnServer Method (Application Object). This method is only valid if you have purchased Crystal Reports 6.0 or later.

Syntax
Sub LogOffServer (pDllName As String, pServerName As String,

    [pDatabaseName], [pUserID], [pPassword])
Parameters

Parameter | Description
pDLLName | Specifies the name of the DLL for the server or password protected non-SQL table you want to log on to, for example "PDSODBC.DLL". Note that the DLLName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases, PDS*.DLL for SQL/ODBC databases.
pServerName | Specifies the log on name for the server used to create the report. (For ODBC, use the data source name.) This value is case-sensitive. See Remarks below.
[pDatabaseName] | Specifies the name for the database used to create the report. See Remarks below.
[pUserID] | Specifies the User ID number necessary to log on to the server. See Remarks below.
[pPassword] | Specifies the password necessary to log on to the server.

Remarks
  • For parameters pServerName, pDatabaseName, and pUserId, pass an empty string ("") to preserve the existing setting or pass a non-empty string (for example, "Server A") to override a value that is already set in the report.
  • If you try to log off a server that is still in use (i.e., there is an object variable still in focus that holds reference to a report that requires being logged on to the server to access data) you will be unable to log off. This will apply to every object that comes from the Report Object, as they all hold reference to the report through their respective Report properties.
  • If you assign the Report object to the ReportSource property of the CRViewer Object (CRVIEWERLib), in the Crystal Reports Report Viewer, enabling the report to be displayed through the Report Viewer, you cannot call LogOffServer for the report until you assign a new report to the Report Viewer or close the CRViewer object.


LogOnServer Method (Application Object)

The LogOnServer method logs on to an SQL server or other data sources such as ODBC. Once logged on using this method, you will remain logged on until you call LogOffServer Method (Application Object), or until the Application Object, is destroyed and craxdrt.dll is unloaded. This method is only valid if you have purchased Crystal Reports 6.0 or later.

Syntax
Sub LogOnServer (pDllName As String, pServerName As String,

    [pDatabaseName], [pUserID], [pPassword])
Parameters

Parameter | Description
pDLLName | Specifies the name of the DLL for the server or password protected non-SQL table you want to log on to, for example "PDSODBC.DLL". Note that the dllName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases, PDS*.DLL for SQL/ODBC databases.
pServerName | Specifies the log on name for the server used to create the report. (For ODBC, use the data source name.) This value is case-sensitive. See Remarks below.
[pDatabaseName] | Specifies the name for the database used to create the report. See Remarks below.
[pUserID] | Specifies the User ID number necessary to log on to the server. See Remarks below.
[pPassword] | Specifies the password necessary to log on to the server.

*When you pass an empty string ("") for this parameter, the program uses the value that's already set in the report. If you want to override a value that's already set in the report, use a non-empty string (i.e., "Server A").

Remarks

For parameters pServerName, pDatabaseName, and pUserId, pass an empty string ("") to preserve the existing setting or pass a non-empty string (for example, "Server A") to override a value that is already set in the report.


LogOnServerEx Method (Application Object)

The LogOnServer method logs on to an SQL server or other data sources such as ODBC. Using LogOnServerEx, you can pass server type or connection information. Once logged on using this method, you will remain logged on until you call LogOffServer Method (Application Object), or until the Application Object, is destroyed and craxdrt.dll is unloaded. This method is only valid if you have purchased Crystal Reports 6.0 or later.

Syntax
Sub LogOnServerEx (pDllName As String, pServerName As String,

    [pDatabaseName], [pUserID], [pPassword],

    [pServerType], [pConnectionString])
Parameters

Parameter | Description
pDLLName | Specifies the name of the DLL for the server or password protected non-SQL table you want to log on to, for example "PDSODBC.DLL". Note that the dllName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases, PDS*.DLL for SQL/ODBC databases.
pServerName | Specifies the log on name for the server used to create the report. (For ODBC, use the data source name.) This value is case-sensitive. See Remarks below.
[pDatabaseName] | Specifies the name for the database used to create the report. See Remarks below.
[pUserID] | Specifies the User ID number necessary to log on to the server. See Remarks below.
[pPassword] | Specifies the password necessary to log on to the server.
[pServerType] | Specifies the database Server Type.
[pConnectionString] | Specifies the connection string.


NewReport Method (Application Object)

The NewReport method creates a new empty Report Object.

Syntax

Function NewReport () As Report

Returns
  • Returns a new empty Report Object.


OpenReport Method (Application Object)

The OpenReport method opens an existing report file, creating an instance of the Report object. Through the Report Object, you can change formatting, formulas, selection formulas, and sort fields for the report, then print, preview, or export the report.

Syntax

Function OpenReport (pFileName As String, [OpenMethod]) As Report

Parameters

Parameter | Description
pFileName | Specifies a string value indicating the file name and path of the report that you want to open.
OpenMethod | Specifies whether you want to open the report exclusively. If you do not provide this parameter the report is opened exclusively and cannot open it a second time.

Returns
  • Returns an instance of the Report Object, if the report was successfully opened.
  • Returns 0 if the report file does not exist or if an error occurs.


SetMatchLogOnInfo Method (Application Object)

The SetMatchLogOnInfo Method sets global match log on info option, matching the log on password.

Syntax

Sub SetMatchLogOnInfo (bl As Boolean)

Parameter

Parameter | Description
bl | Specifies whether the option is selected (TRUE).


SetMorePrintEngineErrorMessages Method (Application Object)

Use the SetMorePrintEngineErrorMessages method to set the global more print engine error messages option.

Syntax

Sub SetMorePrintEngineErrorMessages (bl As Boolean)

Parameter

Parameter | Description
bl | Specifies whether the option is selected (TRUE)


Area Object

The Area Object represents an area in a report. An area is a group of like sections in the report (i.e., Details A - Da, Details B - Db, etc.) that all share the same characteristics. Each section within the area can be formatted differently. This object allows you to retrieve information and set options for a specified area in your report.

Area Object Properties

Property | Description | Read/Write | Restriction in event handler
CopiesToPrint | Integer. Gets or sets the number of copies of each item in the Details section of the report. For example, by default, each line of the Details section only prints once. By setting this to 3, each line of the Details section would print 3 times. | Read/Write | Can be written only when formatting idle.
DetailHeight | Long. Gets the mailing label report deatil area height, in twips. | Read only | None
DetailWidth | Long. Gets multiple column report detail area width, in twips. | Read only | None
DiscardOther Groups | Boolean. Gets or sets the discard other groups option. | Read/Write |
Enable Hierarchical GroupSorting | Boolean. Gets or sets group hierarchically flag. | Read/Write | Fromatting idle.
GroupCondition | CRGroupCondition. Gets or sets the group condition. | Read/Write | Can be written only when formatting idle.
GroupCondition Field | Object. Gets or sets the group condition field. | Read/Write | Can be written only when formatting idle.
GroupIndent | Long. Gets or sets group indent, in twips. | Read/Write | Fromatting idle.
GroupNumber | Integer. If the area is a group area, this returns the group number. Otherwise, exception is thrown. | Read only | None
HideFor DrillDown | Boolean. Gets or sets hide for drill down option. | Read/Write | Can be written only when formatting idle.
HorizontalGap | Long. Gets the horizontal gaps going across page in a multiple column report. | Read only | None
InstanceIDField | FieldDefinition Object. Gets the instance ID field | Read only | Fromatting idle.
KeepGroup Together | Boolean. Gets or sets the keep group together option. | Read/Write | Can be written only when formatting idle.
KeepTogether | Boolean. Gets or sets the keep area together option. | Read/Write | Can be written only when formatting idle.
Kind | CRAreaKind. Gets which kind of area (for example, Details, Report Header, Page Footer, etc.). | Read only | None
Name | String. Gets or sets the area name. | Read/Write | Can be written only when formatting idle.
NewPageAfter | Boolean. Gets or sets the new page after options. | Read/Write | Can be written only when formatting idle.
NewPageBefore | Boolean. Gets or sets the new page before option. | Read/Write | Can be written only when formatting idle.
NumberOfTop OrBottomN Groups | Integer. Gets or sets the number of top or bottom groups. | Read/Write | Formatting idle.
Parent | Report Object. Gets reference to the parent object. | Read Only | None
ParentIDField | FieldDefinition Object. Gets the parent ID field. | Read only | Formatting idle.
PrintAtBottom OfPage | Boolean. Gets or sets the print at bottom of page option. | Read/Write | Can be written only when formatting idle.
RepeatGroup Header | Boolean. Gets or sets the repeating group header option. | Read/Write | Can be written only when formatting idle.
ResetPage NumberAfter | Boolean. Gets or sets the reset page number after option. | Read/Write | Can be written only when formatting idle.
Sections | Sections Collection. Gets a Collection of all the sections in the area. | Read Only | None
SortDirection | CRSortDirection. Gets or sets the group sort direction. | Read/Write | Can be written only when formatting idle.
Suppress | Boolean. Gets or sets the area visibility. | Read/Write | Can be written only when formatting idle.
TopOrBottom NGroupSort Order | CRTopOrBottomNGroupSortOrder. Gets or sets the top or bottom N group sort order. | Read/Write | Formatting idle.
TopOrBottom NSortField | SummaryFieldDefinition Object. Gets or sets the top or bottom n sort field. | Read/Write | Formatting idle.


Area Object Methods

The following methods are discussed in this section:

SetInstanceIDField Method (Area Object)

SetParentIDField (Area Object)


SetInstanceIDField Method (Area Object)

Use SetInstanceIDField method to set an instance ID field.

Syntax

Sub SetInstanceIDField (InstanceIDField)

Parameter

Parameter | Description
InstanceIDField | Specifies the instance ID field that you want to set.


SetParentIDField (Area Object)

Use SetParentIDField method to set the parent ID field.

Syntax

Sub SetParentIDField (ParentIDField)

Parameter

Parameter | Description
ParentIDField | Specifies the parent ID field that you want to set.


Areas Collection

The Areas Collection contains the area objects for every area in the report. Access a specific Area Object, in the collection using the Item property.

Areas Collection Properties

Property | Description | Read/Write | Restriction in event handler
Count | Long. Gets the number of areas in the collection. | Read only | None
Item (index) | Area Object. Gets an item from the Collection. Item has an index parameter that can be either a string reference to the area (for example, "RH", "PH", "GHn", "D", "GFn", "PF", or "RF") or a numeric, 1-based index (for example, Item (1) for the Report Header area). The items in the collection are indexed in the order they are listed for each section/area. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None

Remarks

Instead of using the Item property as shown, you can reference an area directly (for example, Areas("RH") or Areas(1)).


BlobFieldObject Object

The BlobFieldObject Object allows you to get and set information for bitmap database fields in a report.

BlobFieldObject Object Properties

Property | Description | Read/Write | Restriction in event handler
BackColor | OLE_COLOR. Gets or sets the object background color. | Read/Write | Can be written only when formatting idle or active.
BorderColor | OLE_COLOR. Gets or sets the object border color. | Read/Write | Can be written only when formatting idle or active.
BottomCropping | Long. Gets or sets bottom cropping size, in twips. | Read/Write | Can be written only when formatting idle.
BottomLineStyle | CRLineStyle. Gets or sets the bottom line style. | Read/Write | Can be written only when formatting idle or active.
CloseAtPageBreak | Boolean. Gets or sets the close border on page break. | Read/Write | Can be written only when formatting idle or active.
Field | DatabaseFieldDefinition Object. Gets the database field definition object containing information about the BLOB field. | Read only | None
HasDropShadow | Boolean. Gets or sets the border drop shadow option. | Read/Write | Can be written only when formatting idle or active.
Height | Long. Gets or sets the object height, in twips. | Read/Write | Can be written only when formatting idle or active.
KeepTogether | Boolean. Gets or sets the keep object together option. | Read/Write | Can be written only when formatting idle or active.
Kind | CRObjectKind. Gets CRObjectKind which specifies the kind of object (for example, box, cross-tab, field, etc.). | Read only | None
Left | Long. Gets or sets the object upper left position, in twips. | Read/Write | Can be written only when formatting idle or active.
LeftCropping | Long. Gets or sets the left cropping size, in twips. | Read/Write | Can be written only when formatting idle.
LeftLineStyle | CRLineStyle. Gets or sets the left line style. | Read/Write | Can be written only when formatting idle or active.
Name | String. Gets or sets the object name. | Read/Write | Can be written only when formatting idle.
Parent | Section Object. Gets reference to the parent object. | Read only | None
RightCropping | Long. Gets or sets the right cropping size, in twips. | Read/Write | Can be written only when formatting idle.
RightLineStyle | CRLineStyle. Gets or sets the right line style. | Read/Write | Can be written only when formatting idle or active.
Suppress | Boolean. Gets or sets the object visibility. | Read/Write | Can be written only when formatting idle or active.
Top | Long. Gets or sets the object upper top position, in twips. | Read/Write | Can be written only when formatting idle or active.
TopCropping | Long. Gets or sets the top cropping size, in twips. | Read/Write | Can be written only when formatting idle.
TopLineStyle | CRLineStyle. Gets or sets the top line style. | Read/Write | Can be written only when formatting idle or active.
Width | Long. Gets or sets the object width, in twips. | Read/Write | Can be written only when formatting idle or active.
XScaling | Double. Gets or sets the width scaling factor. For example, 1 means 100%, 2 means 200%, 0.5 means 50% etc. The scaling factor may range from 0.01 to 100. | Read/Write | Can be written only when formatting idle.
YScaling | Double. Gets or sets the height scaling factor. For example, 1 means 100%, 2 means 200%, 0.5 means 50% etc. The scaling factor may range from 0.01 to 100. | Read/Write | Can be written only when formatting idle.


BoxObject Object

The Box Object represents a box that has been drawn on the report. This object allows you to get information about boxes in a report.

BoxObject Object Properties

Property | Description | Read/Write | Restriction in event handler
Bottom | Long. Gets or sets the object lower bottom position, in twips. | Read/Write | Can be written only when formatting idle.
BottomRightSection | Section Object. Gets the bottom right section. | Read only | Can be written only when formatting idle.
CloseAtPageBreak | Boolean. Gets or sets the close border on page break option. | Read/Write | Can be written only when formatting idle.
CornerEllipseHeight | Long. Gets or sets the corner elipse height, in twips. | Read/Write |
CornerEllipseWidth | Long. Gets or sets the corner elipse width, in twips. | Read/Write |
ExtendToBottomOf Section | Boolean. Gets or sets the extend to bottom of section option. | Read/Write | Can be written only when formatting idle.
FillColor | OLE_COLOR. Gets or sets the fill color. | Read/Write | Can be written only when formatting idle.
HasDropShadow | Boolean. Gets or sets the border drop shadow option.. | Read/Write | Can be written only when formatting idle.
Kind | CRObjectKind. Gets which kind of object (for example, box, cross-tab, field, etc.). | Read only | None
Left | Long. Gets or sets the upper left position, in twips. | Read/Write | Can be written only when formatting idle or active.
LineColor | OLE_COLOR. Gets or sets the line color. | Read/Write | Can be written only when formatting idle.
LineStyle | CRLineStyle. Gets or sets the line style. | Read/Write | Can be written only when formatting idle.
LineThickness | Long. Gets or sets the line thickness, in twips. | Read/Write | Can be written only when formatting idle.
Name | String. Gets or sets the object name. | Read/Write | Can be written only when formatting idle.
Parent | Section Object. Gets reference to the parent object. | Read only | None
Right | Long. Gets or sets the object lower right position, in twips. | Read/Write | Can be written only when formatting idle.
Suppress | Boolean. Gets or sets the object visibility. | Read/Write | Can be written only when formatting idle or active.
Top | Long. Gets or sets the object upper top position, in twips. | Read/Write | Can be written only when formatting idle or active.


CrossTabGroup Object

The CrossTabGroup Object contains information related to CrossTabGroups in a report.

CrossTabGroup Properties

Property | Description | Read/Write | Restriction in event handler
BackColor | OLE_COLOR. Gets or sets the crosstab group background color. | Read/Write | Idle
Condition | CRGroupCondition. Gets or sets the crosstab group condition. | Read/Write | Idle
EnableSuppress Label | Boolean. Gets or sets the crosstab group enable suppress label option. | Read/Write | Idle
EnableSuppress Subtotal | Boolean. Gets or sets the crosstab group enable suppress subtotal option. | Read/Write | Idle
Field | FieldDefinition Object. Gets or sets the crosstab group's field. | Read/Write | Idle
Parent | CrossTabObject Object. Gets reference to the crosstab group parent object. | Read only | None
SortDirection | CRSortDirection. Gets or sets the crosstab group sort direction. | Read/Write | Idle


CrossTabGroups Collection

The CrossTabGroups Collection contains CrossTabGroup Objects associated with a report.

CrossTabGroups Collection Properties

Property | Description | Read/Write | Restriction in event handler
Count | Long. Gets the CrossTabGroup count. | Read only | None
Item (index As Long) | CrossTabGroup Object. Gets an item from the Collection. | Read only | None
Parent | CrossTabObject Object. Gets reference to the parent object. | Read only | None


CrossTabGroups Collection Methods

The following methods are discussed in this section:

Add Method (CrossTabGroups Collection)

Delete Method (CrossTabGroups Collection)


Add Method (CrossTabGroups Collection)

Use the Add method to add a field as a CrossTabGroup to the CrossTabGroups Collection.

Syntax

Function Add (Field) As CrossTabGroup

Parameter

Parameter | Description
Field | Specifies the field that you want to add as a CrossTabGroup to the Collection.

Returns

Returns a CrossTabGroup Object member of the Collection.


Delete Method (CrossTabGroups Collection)

Use Delete method to remove a CrossTabGroup Object from the Collection.

Syntax

Sub Delete (index As Long)

Parameter

Parameter | Description
index | Specifies the index of the CrossTabGroup Object that you want to delete from the Collection.


CrossTabObject Object

The CrossTabObject Object allows you to get and set information for cross-tab objects in a report.

CrossTabObject Object Properties

Property | Description | Read/Write | Restriction in event handler
BackColor | OLE_COLOR. Gets or sets the object background color. | Read/Write | Can be written only when formatting idle or active.
BorderColor | OLE_COLOR. Gets or sets the object border color. | Read/Write | Can be written only when formatting idle or active.
BottomLineStyle | CRLineStyle. Gets or sets the bottom line style. | Read/Write | Can be written only when formatting idle or active.
CloseAtPageBreak | Boolean. Gets or sets the close border on page break option. | Read/Write | Can be written only when formatting idle or active.
ColumnGrandTotal Color | OLE_COLOR. Gets or sets the column grand total color. | Read/Write | Idle
ColumnGroups | CrossTabGroups Collection. Gets the column groups Collection. | Read only | None
EnableKeep ColumnsTogether | Boolean. Gets or sets the enable keep columns together option. | Read/Write | Idle
EnableRepeatRow Labels | Boolean. Gets or sets the enable repeat row labels option. | Read/Write | Idle
EnableShowCell Margins | Boolean. Gets or sets the enable show cell margins option. | Read/Write | Idle
EnableShowGrid | Boolean. Gets or sets the enable show grid option. | Read/Write | Idle
EnableSuppress ColumnGrand Totals | Boolean. Gets or sets the enable suppress column grand totals option. | Read/Write | Idle
EnableSuppress EmptyColumns | Boolean. Gets or sets the enable suppress empty columns option. | Read/Write | Idle
EnableSuppress EmptyRows | Boolean. Gets or sets the enable suppress empty rows option. | Read/Write | Idle
EnableSuppress RowGrandTotals | Boolean. Gets or sets the enable suppress row grand totals option. | Read/Write | Idle
HasDropShadow | Boolean. Gets or sets the border drop shadow option. | Read/Write | Can be written only when formatting idle or active.
Height | Long. Gets the object height, in twips. | Read only | Can be written only when formatting idle or active.
KeepTogether | Boolean. Gets or sets the keep object together option. | Read/Write | Can be written only when formatting idle or active.
Kind | CRObjectKind. Gets which kind of object (for example, box, cross-tab, field, etc.). | Read only | None
Left | Long. Gets or sets the upper left position, in twips. | Read/Write | Can be written only when formatting idle or active.
LeftLineStyle | CRLineStyle. Gets or sets the left line style. | Read/Write | Can be written only when formatting idle or active.
Name | String. Gets or sets the object name. | Read/Write | Can be written only when formatting idle.
Parent | Section Object. Gets reference to the parent object. | Read only | None
RightLineStyle | CRLineStyle. Gets or sets the right line style. | Read/Write | Can be written only when formatting idle or active.
RowGrandTotal Color | OLE_COLOR. Gets or sets the row grand total color. | Read/Write | Idle
RowGroups | CrossTabGroups Collection. Gets the row groups Collection. | Read Only | None
SummaryFields | ObjectSummaryFieldDefinitions Collection. Gets the summary fields. | Read Only | None
Suppress | Boolean. Gets or sets the object visibility option. | Read/Write | Can be written only when formatting idle or active.
Top | Long. Gets or sets the object upper top position, in twips. | Read/Write | Can be written only when formatting idle or active.
TopLineStyle | CRLineStyle. Gets or sets top line style. | Read/Write | Can be written only when formatting idle or active.
Width | Long. Gets the object width, in twips. | Read Only | Can be written only when formatting idle or active.


Database Object

The Database Object provides properties to get information about the database accessed by a report. See Overview of the Report Designer Object Model.

Database Object Properties

Property | Description | Read/Write | Restriction in event handler
Links | TableLinks Collection. Gets database link collection. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None
Tables | DatabaseTables Collection. Gets the DatabaseTables Collection which specifies the database objects used in the report (for example, an Access report may contain a query or a SQL Server report may be based on a stored procedure - if so, they will be returned as part of this collection along with the database table used in the report). | Read only | None


Database Object Methods

The following methods are discussed in this section:

AddADOCommand Method (Database Object)

AddOLEDBSource Method (Database Object)

ConvertDatabaseDriver Method (Database Object) LogOffServer Method (Database Object)

LogOnServer Method (Database Object)

LogOnServerEx Method (Application Object)

SetDataSource Method (Database Object)

Verify Method (Database Object)


AddADOCommand Method (Database Object)

Use AddADOCommand method to add a database table to your report through an ADO connection and command.

Syntax

Sub AddADOCommand (pConnection, pCommand)

Parameters

Parameter | Description
pConnection | Specifies the ADO connection that you want to use.
pCommand | Specifies the ADO command that you want to use.


AddOLEDBSource Method (Database Object)

Use AddOLEDBSource method to add a database table to your report through an OLE DB provider.

Syntax

Sub AddOLEDBSource (pConnectionString As String, pTableName As String)

Parameters

Parameter | Description
pConnectionString | Specifies the connection string for the OLE DB provider.
pTableName | Specifies the OLE DB database table that you want to add to your report.


ConvertDatabaseDriver Method (Database Object)

Use ConvertDatabaseDriver to convert the database driver DLL used by the report.

Syntax

Sub ConvertDatabaseDriver (pDLLName As String, blDoImmediateConvert as Boolean)

Parameters

Parameter | Description
pDllName | Specifies the new DLL for the database driver.
blDoImmediateConvert | Specifies when the database driver will be converted. If True, the database driver is converted when the report is previewed, or the when the database is verified. If False, the database driver is converted when the report is refreshed in the preview window.

Remarks
  • Set blDoImmediate to False when you want the user to be prompted for the data source information. This applies to reports that are previewed and refreshed in the Crystal Report Viewer, and to reports that are exported or saved to a Crystal Report format (.rpt), and previewed and refreshed in the Crystal Reports Designer. When the report is previewed, a dialog box for the new data source appears. For example, converting to ODBC (P2sodbc.dll) opens the Set Data Source dialog box, while converting to OLEDB (P2soledb.dll) opens the Data Link Properties dialog box.
  • Set blDoImmediateConvert to True when you want to set the data source at runtime. Additional code must be added to set the logon information for the data source, and to verify the database. One exception is converting to OLEDB (P2soledb.dll). Since there is no method to set the provider at runtime the Data Links dialog box will always prompt for the data source. In this case only the code to convert the databse driver is required.
  • Once the database is converted, and the data source is set, either through code, or through a dialog box, three additional prompts may appear:
      • Logon to the data source
        This dialog box allows you to log on to the correct data source. If the data source is not secured, you can click OK without entering any logon information.
      • Verify the database
        This is a message warning the user that the database file has changed and the report is being updated.
      • Map the fields.
        This dialog box allows you to map the fields that have changed with the new data source. For more information on mapping fields see "Re-mapping altered database fields" in the Crystal Reports Online Help (Crw.chm).
Sample

The following code demonstrates how to convert the database driver to ODBC (P2sodbc.dll) using the ConverDataBaseDriver method. The ODBC data source is pointing to a Microsoft Access database.

'Instantiate the report object.
Set m_Report = New CrystalReport1

' Convert the database driver to ODBC.
m_Report.Database.ConvertDatabaseDriver "p2sodbc.dll", True

' Set the logon information for the ODBC data source.
' If the logon information is not set an error will be produced when the
' report is previewed or exported.
m_Report.Database.Tables(1).SetLogOnInfo "Xtreme Sample Database", "",
"", ""

' Verify the database.
' If the database is not verified before exporting an error will be
produced.
' If the database is not verified before previewing the report, the user
may be
' prompted when the report is refreshed in the Crystal Report Viewer.
m_Report.Database.Verify


LogOffServer Method (Database Object)

The LogOffServer method logs off an SQL server, ODBC or other data source. Use this method when you have logged on to the data source using LogOnServer. This method can be invoked only in formatting Idle mode.

Syntax
Sub LogOffServer (pDllName As String, pServerName As String,

    [pDatabaseName], [pUserID], [pPassword])
Parameters

Parameter | Description
pDllName | Specifies the name of the DLL for the server or password protected non-SQL table you want to log on to, for example "PDSODBC.DLL". Note that the dllName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases, PDS*.DLL for SQL/ODBC databases.
pServerName | Specifies the log on name for the server used to create the report. For ODBC, use the data source name. This value is case-sensitive. See Remarks below.
[pDatabaseName] | Specifies the name for the database used to create the report. See Remarks below.
[pUserID] | Specifies the User ID number necessary to log on to the server. See Remarks below.
[pPassword] | Specifies the password necessary to log on to the server.

Remarks
  • When you pass an empty string ("") for pServerName, pDatabaseName, or pUserID, the program uses the value that's already set in the report. If you want to override a value that's already set in the report, use a non-empty string (for example, "Server A").
  • If you try to log off a server that is still in use (that is, there is an object variable still in focus that holds reference to a report that requires being logged on to the server to access data) you will be unable to log off. This will apply to every object that comes from the Report Object, as they all hold reference to the report through their respective Report properties.
  • If you assign the Report object to the ReportSource property of the CRViewer Object (CRVIEWERLib), in the Crystal Reports Report Viewer, enabling the report to be displayed through the Report Viewer, you cannot call LogOffServer for the report until you assign a new report to the Report Viewer or close the CRViewer object.


LogOnServer Method (Database Object)

The LogOnServer method logs on to an SQL server, ODBC or other data source. Once logged on using this method, you will remain logged on until you call LogOffServer or until the Application Object is destroyed and craxdrt.dll is unloaded. This method can be invoked only in formatting Idle mode.

Syntax
Sub LogOnServer (pDllName As String, pServerName As String,

    [pDatabaseName], [pUserID], [pPassword])
Parameters

Parameter | Description
pDllName | Specifies the name of the DLL for the server or password protected non-SQL table you want to log on to, for example "PDSODBC.DLL". Note that the dllName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases, PDS*.DLL for SQL/ODBC databases.
pServerName | Specifies the log on name for the server used to create the report. For ODBC, use the data source name. This value is case-sensitive. See Remarks below.
[pDatabaseName] | Specifies the name for the database used to create the report. See Remarks below.
[pUserID] | Specifies the User ID number necessary to log on to the server. See Remarks below.
[pPassword] | Specifies the password necessary to log on to the server.

Remarks

When you pass an empty string ("") for this parameter, the program uses the value that's already set in the report. If you want to override a value that's already set in the report, use a non-empty string (for example, "Server A").


LogOnServerEx Method (Database Object)

The LogOnServerEx method logs on to an SQL server, ODBC or other data source. Using this method, you can pass ServerType and ConnectionString info. Once logged on using this method, you will remain logged on until you call LogOffServer or until the Application Object is destroyed and craxdrt.dll is unloaded. This method can be invoked only in formatting Idle mode.

Syntax
Sub LogOnServerEx (pDllName As String, pServerName As String,

    [pDatabaseName], [pUserID], [pPassword],

    [pServerType], [pConnectionString])
Parameters

Parameter | Description
pDllName | Specifies the name of the DLL for the server or password protected non-SQL table you want to log on to, for example "PDSODBC.DLL". Note that the dllName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases, PDS*.DLL for SQL/ODBC databases.
pServerName | Specifies the log on name for the server used to create the report. For ODBC, use the data source name. This value is case-sensitive. See Remarks below.
[pDatabaseName] | Specifies the name for the database used to create the report. See Remarks below.
[pUserID] | Specifies the User ID number necessary to log on to the server. See Remarks below.
[pPassword] | Specifies the password necessary to log on to the server.
[pServerType] | Specifies the database Server Type.
[pConnectionString] | Specifies the connection string.

Remarks

When you pass an empty string ("") for this parameter, the program uses the value that's already set in the report. If you want to override a value that's already set in the report, use a non-empty string (for example, "Server A").


SetDataSource Method (Database Object)

The SetDataSource method is used to provide information about a data source to the database driver associated with this Database object at runtime. For instance, if a report has been designed using the Crystal Active Data Driver this method can be used to provide an active data source for the report, such as a DAO, ADO, or RDO Recordset or a CDO Rowset. In this case, the object passed to the second parameter of this method replaces, at runtime, the field definition file used to create the report. This method can be invoked only in formatting Idle mode. When using a secure connection such as SQL Server, some additional code is required (see Remarks below).

Syntax

Sub SetDataSource (data, [dataTag], [tableNumber])

Parameters

Parameter | Description
data | Variant data passed to the database driver. For example, with Active data, this must be a Recordset object if you are using DAO, ADO, or the Visual Basic data control. This must be a Rowset object if you are using CDO.
[dataTag] | A value indicating the type of data being passed to the DatabaseTable object in the Data parameter. Currently, the only possible value is 3. This value must be used for all Active data sources including DAO, ADO, RDO, CDO, and the Visual Basic data control.
[tableNumber] | Specifies the index number of the table to be set. Default value = 1.

Remarks
  • When the data source uses a secure connection, such as SQL Server, additional information must be passed in the "form load" event before the call to view the report. For example,

    DataEnvironment1.Command1

    Report.Database.SetDataSource (DataEnvironment1.rsCommand1)

  • SetDataSource method is used to set a datasource at runtime. If the report is initially created and then saved, and then later run using either the RDC or CRW, the runtime datasource (DAO, ADO, or RDO Recordset) cannot be recreated. The user will not be able to run or preview the report.


Verify Method (Database Object)

The Verify method verifies that the location of the database is still valid and checks to see if any changes have been made to table design, etc. If there are any changes to the database, the Verify method will update the report automatically to reflect these changes. See Remarks below. This method can be invoked only in formatting Idle mode.

Syntax

Sub Verify ()

Remarks

Prior to calling Verify, you can use the CheckDifferences Method (DatabaseTable Object) to determine what kind of differences, if any, exist between the report table and the physical table. pDifferences parameter of CheckDifferences method will pass back one or more bitwise (XOR'd) CRTableDifferences enums indicating the information that you want to retrieve.


DatabaseFieldDefinition Object

The DatabaseFieldDefinition Object represents a database field used in the report. This object provides properties for getting information on database fields in the report.

DatabaseFieldDefinition Object Properties

Property | Definition | Read/Write | Restriction in event handler
DatabaseFieldName | String. Specifies the name of the field in the database (for example, Product ID). | Read only | None
Kind | CRFieldKind. Gets which kind of field (for example, database, summary, formula, etc.). | Read only | None
Name | String. Gets the unique Crystal formula form name of the field within the report as {table.FIELD} (for example, {product.PRODUCT ID}). | Read only | None
NextValue | Variant. Gets the field next value. | Read only | Can be read only when top-level Report object is formatting active.
NumberOfBytes | Integer. Gets the number of bytes required to store the field data in memory. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None
PreviousValue | Variant. Gets the field previous value. | Read only | Can be read only when top-level Report object is formatting active.
TableAliasName | String. Gets the alias for the table containing the field. | Read only | Can be written only when formatting idle.
Value | Variant. Gets the field current value. | Read only | Can be read only when top-level Report object is formatting active.
ValueType | CRFieldValueType. Gets which type of value is found in the field. | Read only | None


DatabaseFieldDefinitions Collection

The DatabaseFieldDefinitions Collection is a collection of database field definition objects. One object exists in the collection for every database field accessed by the report. Access a specific DatabaseFieldDefinition Object in the collection using the Item property.

DatabaseFieldDefinitions Collection Properties

Property | Description | Read/Write | Restriction in event handler
Count | Long. Gets the number of DatabaseFieldDefinition Object, in the collection. | Read only | None
Item (index As Long) | DatabaseFieldDefinition Object. Item has an index parameter that is a numeric, 1-based index for the object that you want to retrieve (for example, Item (1) for the first database field in the collection). The items in the collection are indexed in the order they appear in the database table. | Read only | None
Parent | DatabaseTable Object. Reference to the parent object. | Read only | None

Remarks

Instead of using the Item property as shown, you can reference a database directly (for example, DatabaseFieldDefintion(1)).


DatabaseTable Object

The DatabaseTable Object refers to a database table accessed by the report.

DatabaseTable Object Properties

Property | Description | Read/Write | Restriction in event handler
ConnectBuffer String | String. Gets the table connect buffer string. | Read only | None
DatabaseType | CRDatabaseType. Gets the database table type | Read only |
DescriptiveName | String. Gets the table descriptive name. | Read only | None
DllName | String. Gets the table driver DLL name. | Read only | None
Fields | DatabaseFieldDefinitions Collection. Gets the collection of database fields in the table. | Read only | None
Location | String. Gets or sets the location of the database table. | Read/Write | Can be written only when formatting idle.
LogOnDatabase Name | String. Gets the logon database name. | Read only | None
LogOnServerName | String. Gets the logon server name. | Read only | None
LogOnUserID | String. Gets the logon user ID. | Read only | None
Name | String. Gets or sets the alias name for the database table used in the report. | Read/Write | Can be written only when formatting idle.
Parent | Database Object. Reference to the parent object. | Read only | None
SessionUserID | String. Gets the session user ID. | Read only | None
SubLocation | String. Gets the table sublocation. | Read only | None


DatabaseTable Object Methods

The following methods are discussed in this section:

CheckDifferences Method (DatabaseTable Object)

SetDataSource Method (DatabaseTable Object)

SetLogOnInfo Method (DatabaseTable Object)

SetSessionInfo Method (DatabaseTable Object)

SetTableLocation Method (DatabaseTable Object)

TestConnectivity Method (DatabaseTable Object)


CheckDifferences Method (DatabaseTable Object)

Use CheckDifferences method to determine what kind(s) of differences were found between the report table and the physical table.

Syntax

Sub CheckDifferences (pDifferences As Long, [reserved])

Parameters

Parameter | Description
pDifferences | CRTableDifferences. Bitwise constants specify the table difference(s) (XOR'd), if any.
[reserved] | Reserved. Do not use.


SetDataSource Method (DatabaseTable Object)

The SetDataSource method is used to provide information about a data source to the database driver associated with this DatabaseTable object at runtime. For instance, if a report has been designed using the Crystal Active Data Driver this method can be used to provide an active data source for the report, such as a DAO, ADO, or RDO Recordset or a CDO Rowset. In this case, the object passed to the second parameter of this method replaces, at runtime, the field definition file used to create the report. This method can be invoked only in formatting Idle mode. When using a secure connection such as SQL Server, some additional code is required (see Remarks below).

Syntax

Sub SetDataSource (data, [dataTag])

Parameters

Parameter | Description
data | Variant data passed to the database driver. For example, with Active data, this must be a Recordset object if you are using DAO, ADO, or the Visual Basic data control. This must be a Rowset object if you are using CDO.
[dataTag] | A value indicating the type of data being passed to the DatabaseTable object in the Data parameter. Currently, the only possible value is 3. This value must be used for all Active data sources including DAO, ADO, RDO, CDO, and the Visual Basic data control.

Remarks
  • When the data source uses a secure connection, such as SQL Server, additional information must be passed in the "form load" event before the call to view the report. For example,

    DataEnvironment1.Command1
    Report.DatabaseTable.SetDataSource (DataEnvironment1.rsCommand1)

  • SetDataSource method is used to set a datasource at runtime. If the report is initially created and then saved, and then later run using either the RDC or CRW, the runtime datasource (DAO, ADO, or RDO Recordset) cannot be recreated. The user will not be able to run or preview the report.


SetLogOnInfo Method (DatabaseTable Object)

The SetLogOnInfo method logs on to the data source so table data can be accessed.

Syntax
Sub SetLogOnInfo (pServerName As String,
[pDatabaseName], [pUserID], [pPassword])
Parameters

Parameter | Description
pServerName | Specifies the name of the server or ODBC data source where the database is located (that is, CRSS).
[pDatabaseName] | Specifies the name of the database.
[pUserID] | Specifies a valid user name for logging on to the data source.
[pPassword] | Specifies a valid password for logging on to the data source.


SetSessionInfo Method (DatabaseTable Object)

The SetSessionInfo method allows the user to log on to a secured Access session.

Syntax

Sub SetSessionInfo (pSessionUserID As String, pSessionPassword As String)

Parameters

Parameter | Description
pSessionUserID | Specifies the Access userID used to log on to an Access session.
pSessionPassword | Specifies the session password for Access secured session.

Remarks

In Microsoft Access 95 and later, an Access database can have session security (also known as user-level security), database-level security, or both. If the Access database contains only session security, simply pass the session password to the SessionPassword parameter. If the Access database contains database-level security, use a linefeed character, Chr(10), followed by the database-level password. For example:

object.SetSessionInfo "userID", Chr(10) & "dbpassword"

If the Access database contains both session security and database-level security, use the session password followed by the linefeed character and the database password.

object.SetSessionInfo "userID", _

        "sesspswd" & Chr(10) & "dbpassword"

Alternately, database-level security can also be handled by assigning the database-level password to the Password parameter of the SetLogOnInfo Method (DatabaseTable Object).


SetTableLocation Method (DatabaseTable Object)

The SetTableLocation method is used to set the DatabaseTable location, sublocation, and connect buffer string.

Syntax
Sub SetTableLocation (pLocation As String, pSubLocation As String,

    pConnectBufferSting As String)
Parameters

Parameter | Description
pLocation | Specifies the location of the database table (file path and name.ext).
pSubLocation | Specifies the sublocation of the database table.
pConnectBufferSting | Specifies the connection buffer string.

Remarks

For example:

object.SetTableLocation "xtreme.mdb", "Customer", ""


TestConnectivity Method (DatabaseTable Object)

The TestConnectivity method tests to see if the database can be logged on to with the current information and if the database table can be accessed by the report.

Syntax

Function TestConnectivity () As Boolean

Returns
  • TRUE if the database session, log on, and location information is all correct.
  • FALSE if the connection fails or an error occurs.


DatabaseTables Collection

The DatabaseTables Collection is a collection of DatabaseTable objects. A DatabaseTable object exists for every database object (for example, table, query, stored procedure, etc.) accessed by the report. Access a specific DatabaseTable Object in the collection using the Item property.

DatabaseTables Collection Properties

Property | Description | Read/Write | Restriction in event handler
Count | Long. Gets the number of database objects in the collection. | Read only | None
Item (index As Long) | DatabaseTable Object. Item has an index parameter that is a numeric, 1-based index (for example, Item (1)). The items in the collection are indexed in the order in which they were added to the report. | Read only | None
Parent | Database Object. Reference to the parent object. | Read only | None

Remarks

Instead of using the Item property as shown, you can reference a table directly (for example, DatabaseTable(1)).


DatabaseTables Collection Methods

The following methods are discussed in this section:

Add Method (DatabaseTables Collection)

Delete Method (DatabaseTables Collection)


Add Method (DatabaseTables Collection)

The Add method is used to add a database table to the report.

Syntax
Sub Add (pLocation As String, [pSubLocation], [pConnectInfo],

    [tableType], [pDllName], [pServerName], [pServerType],

    [pDatabaseName], [pUserID], [pPassword])
Parameters

Parameter | Description
pLocation | Specifies the location of the database table that you want to add to the report.
[pSubLocation] | Specifies the sublocation of the database table that you want to add to the report.
[pConnectInfo] | Specifies the connection string.
[tableType] | Specifies the type of database table that you want to add to the report.
[pDllName] | Specifies the DLL name for the database containing the table that you want to add.
[pServerName] | Specifies the database Server Name.
[pServerType] | Specifies the database Server Type.
[pDatabaseName] | Specifies the database (file path and name.ext) containing the table that you want to add.
[pUserID] | Specifies the User's ID.
[pPassword] | Specifies the User's Password.

Remarks
  • DatabaseTables.Add method is very generic and can be used to add tables to a report from all kinds of data sources (for example, PC Table, SQL Server, ODBC, OLE DB provider, ADO, RDO, DAO Recordset).
  • For example:

object.Add "xtreme.mdb", "Customer"


Delete Method (DatabaseTables Collection)

Use Delete method to remove a database table from the Collection.

Syntax

Sub Delete (index As Long)

Parameter

Parameter | Description
index | Specifies the 1-based index number in the Collection of the database table that you want to delete.


ExportOptions Object

The ExportOptions object provides properties and methods for retrieving information and setting options for exporting your report (that is, export format, destination, etc.). An ExportOptions Object is obtained from the ExportOptions property of the Report Object.

ExportOptions Object Properties

Property | Description | Read/Write | Restriction in event handler
ApplicationFile Name | String. Gets or sets the destination application file name. | Read/Write | Set before exporting report to an application destination.
CharFieldDelimiter | String. Gets or sets the character used to separate fields in character separated text formats. This character delimits every field in the file. | Read/Write | None
CharStringDelimiter | String. Gets or sets the character used to separate strings in character separated text formats. This character delimits only string fields (numeric, date fields, etc., have no delimiter). | Read/Write | None
DestinationDLL Name | String. Gets the Internal Name property of the DLL used to export the report to a certain destination. The destination is set in the DestinationType property. | Read only | None
DestinationType | CRExportDestinationType. Gets or sets the export destination type. | Read/Write | None
DiskFileName | String. Gets or sets the file name if the report is exported to a disk. When exporting to HTML use HTMLFileName. When exporting to XML use XMLFileName. | Read/Write | None
ExcelAreaGroup Number | Integer. Gets or sets the base area group number if the area type is group area when exporting to Excel. | Read/Write | None
ExcelAreaType | CRAreaKind. Gets or sets the base area type if not using constant column width when exporting to Excel. | Read/Write | None
ExcelConstant ColumnWidth | Double. Gets or sets the column width when exporting to Excel. | Read/Write | None
ExcelTabHas ColumnHeadings | Boolean. Gets or sets exporting to Excel has column headings option. | Read/Write | None
ExcelUseConstant ColumnWidth | Boolean. Gets or sets export to Excel to use constant column width. | Read/Write | None
ExcelUseTabular Format | Boolean. Gets or sets exporting to Excel to use tabular format. | Read/Write | None
ExcelUseWorksheet Functions | Boolean. Gets or sets export to Excel to use worksheet functions to represent subtotal fields in the report. | Read/Write | None
Exchange DestinationType | CRExchangeDestinationType. Gets or sets the Exchange destination type for reports exported to Exchange folders. | Read/Write | None
ExchangeFolderPath | String. Gets or sets the path of the Exchange folder for reports exported to Exchange (for example, "MyFolders@Inbox"). | Read/Write | None
ExchangePassword | String. Sets Exchange password. | Write only | None
ExchangeProfile | String. Gets or sets a user profile for accessing an Exchange folder for reports exported to Exchange. | Read/Write | None
ExchangePathHas ColumnHeadings | Boolean. Gets or sets the column heading option when exporting to Exchange. | Read/Write | None
FormatDLLName | String. Gets the Internal Name property of the DLL used to export the report to a certain format type. The export format type is set in the FormatType property. | Read only | None
FormatType | CRExportFormatType. Gets or sets the format type for the exported report (for example, text, Excel, etc.). | Read/Write | None
HTMLEnable SeperatedPages | Boolean. Gets or sets the option to create seperated pages when exporting to HTML format. | Read/Write | None
HTMLFileName | String. Gets or sets the HTML file name for reports exported to HTML format. | Read/Write | None
HTMLHasPage Navigator | Boolean. Gets or sets the option to display a page navigator on each page of a report exported to HTML format. | Read/Write | None
LotusDomino Comments | String. Gets or sets the destination Lotus Domino comments. | Read/Write | None
LotusDomino DatabaseName | String. Gets or sets the destination Lotus Domino database name. | Read/Write | None
LotusNotesForm Name | String. Gets or sets the destination Lotus Domino form name. | Read/Write | None
MailBccList | String. Gets or sets a Blind Carbon Copy (BCC) list for reports e-mailed to a VIM e-mail account. | Read/Write | None
MailCcList | String. Gets or sets a Carbon Copy (CC) list for reports e-mailed. | Read/Write | None
MailMessage | String. Gets or sets the e-mail message included with e-mailed reports. | Read/Write | None
MailSubject | String. Gets or sets the e-mail subject heading for reports being e-mailed. | Read/Write | None
MailToList | String. Gets or sets the To list for reports being e-mailed. | Read/Write | None
NumberOfLines PerPage | Integer. Gets or sets the number of lines to appear per page option for reports exported to a paginated text format. | Read/Write | None
ODBC DataSourceName | String. Gets or sets the ODBC data source for reports exported to ODBC. | Read/Write | None
ODBCDataSource Password | String. Sets the ODBC data source password. | Write only | None
ODBCDataSource UserID | String. Gets or sets the user name used to access an ODBC data source for reports exported to ODBC. | Read/Write | None
ODBCExportTable Name | String. Gets or sets the database table in the ODBC data source that the report file exported to ODBC will be appended to. You can also create a new table using this property. | Read/Write | None
PDFExportAllPages | Boolean. Gets or sets wether or not to export all pages of the report to Portable Document Format(PDF). PDFExportAllPages must be set to false when setting PDFFirstPageNumber and PDFLastPageNumber. | Read/Write | None
PDFFirstPage Number | Long. Gets or sets the start page, of a page export range, when exporting to PDF. PDFExportAllPages must be set to False or this value is ignored. | Read/Write | None
PDFLastPage Number | Long. Gets or sets the end page, of a page export range, when exporting to PDF. PDFExportAllPages must be set to False or this value is ignored. | Read/Write | None
Parent | Report Object. Reference to the parent object. | Read only | None
RTFExportAllPages | Boolean. Gets or sets wether or not to export all pages of the report to Rich Text Format(RTF). RTFExportAllPages must be set to false when setting RTFFirstPageNumber and RTFLastPageNumber. | Read/Write | None
RTFFirstPage Number | Long. Gets or sets the start page, of a page export range, when exporting to RTF. RTFExportAllPages must be set to False or this value is ignored. | Read/Write | None
RTFFLastPage Number | Long. Gets or sets the end page, of a page export range, when exporting to RTF. RTFExportAllPages must be set to False or this value is ignored. | Read/Write | None
UseReportDate Format | Boolean. Gets or sets whether the date format used in the report should also be used in the exported report. Can be used for Data Interchange Format (DIF), Record Style Format, and comma, tab, or character separated format. | Read/Write | None
UseReportNumber Format | Boolean. Gets or sets whether the number format used in the report should also be used in the exported report. Can be used for Data Interchange Format (DIF), Record Style Format, and comma, tab, or character separated format. | Read/Write | None
XMLAllowMultiple Files | Boolean. Gets or sets allow multiple files, when exporting to XML. When set to True the Schema file for the report will be exported along with the XML file. The Schema file will be either an XML schema (.xsd) or a Document Type Definition (.dtd), depending on the options selected in the XML Forma dilaog box. For more information see "Customizing XML report definitions" in the Crystal Reports Users Guide. | Read/Write | None
XMLFileName | String. Gets or sets the file name if the report is exported to a disk. | Read/Write | None

Remarks

For backwards compatibility the FormatDllName and DestinationDllName properties return the Internal Name property of the associated DLL. The Internal Name property of the DLL is found in the DLLs Properties Dialog box under the Version tab. For a list of export DLLs see "Export Destination" and "Export Format" in the Runtime help (Runtime.hlp).


ExportOptions Object Methods

The following methods are discussed in this section:

PromptForExportOptions Method (ExportOptions Object)

Reset Method (ExportOptions Object)


PromptForExportOptions Method (ExportOptions Object)

The PromptForExportOptions method prompts the user for export information using default Crystal Report Engine dialog boxes.

Syntax

Sub PromptForExportOptions ()


Reset Method (ExportOptions Object)

The Reset method clears all ExportOptions properties.

Syntax

Sub Reset ()


FieldDefinitions Collection

The FieldDefinitions Collection contains the various types of XXXFieldDefinition Objects (for example, DatabaseFieldDefinition, FormulaFieldDefinition, SummaryFieldDefinition). For the current release, developers can access the FieldDefinitions Collection only through the ConditionFields Property of GraphObject.

FieldDefinitions Collection Properties

Property | Description | Read/Write | Restriction in event handler
Count | Long. Gets the collection count. | Read only | None
Item (index As Long) | FieldDefinition Object. Gets the collection item. | Read only | None
Parent | IReportObject. Reference to the parent object (ReportObject). | Read only | None


FieldDefinitions Collection Methods

The following methods are discussed in this section:

Add Method (FieldDefinitions Collection)

Delete Method (FieldDefinitions Collection)


Add Method (FieldDefinitions Collection)

Use Add method to add the specified Field to the FieldDefinitions Collection.

Syntax

Sub Add (Field)

Parameter

Parameter | Description
Field | Specifies the Field that you want to add to the Collection.


Delete Method (FieldDefinitions Collection)

Use Delete method to remove the specified Field from the FieldDefinitions Collection

Syntax

Sub Delete(Field)

Parameter

Parameter | Description
Field | Specifies the Field that you want to delete from the Collection.


FieldMappingData Object

The FieldMappingData Object provides information related to FieldMapping Events. This Object can be accessed through the Report Object FieldMapping Event.

FieldMappingData Object Properties

Property | Description | Read/Write | Restriction in event handler
FieldName | String. Gets or sets the field name. | Read/Write | None
MappingToField Index | Integer. Gets or sets the index of the mapping to field index in the field list of the new database. | Read/Write | None
TableName | String. Gets or sets field's table name. | Read/Write | None
ValueType | CRFieldValueType. Gets or sets the value type that is in the field. | Read/Write | None


FieldObject Object

The FieldObject Object represents a field found in a report (for example, special field, database field, parameter field, etc.). This object provides properties for retrieving information for a field in your report. A FieldObject Object is obtained from the Item property of the ReportObjects Collection, (for example, ReportObjects.Item(Index), where the index can be the 1-based index number of the item or an Object name).

Property | Description | Read/ Write | Restriction in event handler
AmPmType | CRAMPMType. Gets or sets the AM/PM type option. | Read/Write | Can be written only when formatting idle or active.
AmString | String. Gets or sets the AM string. | Read/Write | Can be written only when formatting idle or active.
BackColor | OLE_COLOR. Gets or sets the object background color. | Read/Write | Can be written only when formatting idle or active.
BooleanOutput Type | CRBooleanOutputType. Gets or sets the Boolean output type. | Read/Write | Can be written only when formatting idle or active.
BorderColor | OLE_COLOR. Gets or sets the object border color. | Read/Write | Can be written only when formatting idle or active.
BottomLineStyle | CRLineStyle. Gets or sets bottom line style. | Read/Write | Can be written only when formatting idle or active.
CanGrow | Boolean. Gets or sets can the grow option. | Read/Write | Can be written only when formatting idle or active.
CharacterSpacing | Long. Gets or sets the character spacing. | Read/Write | Can be written only when formatting idle.
CloseAtPageBreak | Boolean. Gets or sets the close border on page break option. | Read/Write | Can be written only when formatting idle or active.
CurrencyPosition Type | CRCurrencyPositionType. Gets or sets the currency position type. | Read/Write | Can be written only when formatting idle or active.
CurrencySymbol | String. Gets or sets the currency symbol. | Read/Write | Can be written only when formatting idle or active.
CurrencySymbol Type | CRCurrencySymbolType. Gets or sets the currency symbol type. | Read/Write | Can be written only when formatting idle or active.
DateCalendarType | CRDateCalendarType. Gets or sets the date calendar type. | Read/Write | Can be written only when formatting idle.
DateEraType | CRDateEraType. Gets or sets the date era type. | Read/Write | Can be written only when formatting idle.
DateFirstSeparator | String. Gets or sets the date first separator. | Read/Write | Can be written only when formatting idle or active.
DateOrder | CRDateOrder. Gets or sets the date order. | Read/Write | Can be written only when formatting idle or active.
DatePrefixSeparator | String. Gets or sets the date prefix separator. | Read/Write | Can be written only when formatting idle or active.
DateSecond Separator | String. Gets or sets the date second separator. | Read/Write | Can be written only when formatting idle or active.
DateSuffixSeparator | String. Gets or sets the date suffix separator | Read/Write | Can be written only when formatting idle or active.
DateWindows DefaultType | CRDateWindowsDefaultType. Gets or sets the date windows default type. | Read/Write | Can be written only when formatting idle.
DayType | CRDayType. Gets or sets the day type. | Read/Write | Can be written only when formatting idle or active.
DecimalPlaces | Integer. Gets or sets the number decimal places. | Read/Write | Can be written only when formatting idle or active.
DecimalSymbol | String. Gets or sets the decimal symbol. | Read/Write | Can be written only when formatting idle or active.
DisplayReverseSign | Boolean. Gets or sets the reverse sign option. | Read/Write | Can be written only when formatting idle or active.
EnableTight Horizontal | Boolean. Gets or sets the tight horizontal option. | Read/Write | Can be written only when formatting idle or active.
Field | Object. Gets the field definition object (for example, Database FieldDefinition Object, Parameter FieldDefinition Object, etc.). | Read only | None
FirstLineIndent | Long. Gets or sets the first line indent. | Read/Write | Can be written only when formatting idle.
Font | IFontDisp. Gets or sets the standard OLE font. | Read/Write | Can be written only when formatting idle or active.
HasDropShadow | Boolean. Gets or sets the border drop shadow option. | Read/Write | Can be written only when formatting idle or active.
Height | Long. Gets or sets object height, in twips. | Read/Write | Can be written only when formatting idle or active.
HorAlignment | CRAlignment. Gets or sets the horizontal alignment. | Read/Write | Can be written only when formatting idle or active.
HourMinute Separator | String. Gets or sets the hour minute separator. | Read/Write | Can be written only when formatting idle or active.
HourType | CRHourType. Gets or sets the hour type. | Read/Write | Can be written only when formatting idle or active.
KeepTogether | Boolean. Gets or sets the keep object together option. | Read/Write | Can be written only when formatting idle or active.
Kind | CRObjectKind. Gets which kind of object (for example, box, cross-tab, field, etc.). | Read only | None
LeadingDayPosition | CRLeadingDayPosition. Gets or sets the leading day position option. | Read/Write | Can be written only when formatting idle.
LeadingDay Separator | String. Gets or sets the leading day separator. | Read/Write | Can be written only when formatting idle or active.
LeadingDayType | CRLeadingDayType. Gets or sets the leading day type. | Read/Write | Can be written only when formatting idle or active.
Left | Long. Gets or sets the object upper left position, in twips. | Read/Write | Can be written only when formatting idle or active.
LeftIndent | Long. Gets or sets the left indent, in twips. | Read/Write | Can be written only when formatting idle.
LeftLineStyle | CRLineStyle. Gets or sets the left line style. | Read/Write | Can be written only when formatting idle or active.
LineSpacing | Double. Gets the line spacing. | Read Only | None
LineSpacingType | CRLineSpacingType. Gets the line spacing type. | Read Only | None
MaxNumberOf Lines | Integer. Gets or sets the maximum number of line for a string memo field. | Read/Write | Can be written only when formatting idle or active.
MinuteSecond Separator | String. Gets or sets minute second separator. | Read/Write | Can be written only when formatting idle or active.
MinuteType | CRMinuteType. Gets or sets the minute type. | Read/Write | Can be written only when formatting idle or active.
MonthType | CRMonthType. Gets or sets month type. | Read/Write | Can be written only when formatting idle or active.
Name | String. Gets or sets the object name. | Read/Write | Can be written only when formatting idle or active.
NegativeType | CRNegativeType. Gets or sets number negative type. | Read/Write | Can be written only when formatting idle or active.
NextValue | Variant. Gets the field next value. | Read only | Can be written only when formatting idle or active.
Parent | Section Object. Reference to the parent object. | Read only | Can be written only when formatting idle or active.
PmString | String. Gets or sets the PM string. | Read/Write | Can be written only when formatting idle or active.
PreviousValue | Variant. Gets the field previous value. | Read only | Can be written only when formatting idle or active.
RightIndent | Long. Gets or sets the right indent, in twips. | Read/Write | Can be written only when formatting idle.
RightLineStyle | CRLineStyle. Gets or sets the right line style. | Read/Write | Can be written only when formatting idle or active.
RoundingType | CRRoundingType. Gets or sets the number rounding type. | Read/Write | Can be written only when formatting idle or active.
SecondType | CRSecondType. Gets or sets the seconds type. | Read/Write | Can be written only when formatting idle or active.
Suppress | Boolean. Gets or sets the object visibility. | Read/Write | Can be written only when formatting idle or active.
SuppressIf Duplicated | Boolean. Gets or sets the suppress if duplicate option. | Read/Write | Can be written only when formatting idle or active.
SuppressIfZero | Boolean. Gets or sets the suppress if zero option. | Read/Write | Can be written only when formatting idle or active.
TextColor | OLE_COLOR. Gets or sets the object text color. | Read/Write | Can be written only when formatting idle or active.
TextFormat | CRTextFormat. Gets or sets the text format option for string memo fields. | Read/Write | Can be written only when formatting idle.
TextRotationAngle | CRRotationAngle. Gets or sets the text rotation angle. | Read/Write | Can be written only when formatting idle.
Thousands Separators | Boolean. Gets or sets the enable thousands separators option. | Read/Write | Can be written only when formatting idle or active.
ThousandSymbol | String. Gets or sets the thousand separator symbol. | Read/Write | Can be written only when formatting idle or active.
TimeBase | CRTimeBase. Gets or sets the time base. | Read/Write | Can be written only when formatting idle or active.
Top | Long. Gets or sets the object upper top position, in twips. | Read/Write | Can be written only when formatting idle or active.
TopLineStyle | CRLineStyle. Gets or sets the top line style. | Read/Write | Can be written only when formatting idle or active.
UseLeadingZero | Boolean. Gets or sets the number uses leading zero option. | Read/Write | Can be written only when formatting idle or active.
UseOneSymbol PerPage | Boolean. Gets or sets the use one symbol per page option. | Read/Write | Can be written only when formatting idle or active.
UseSystem Defaults | Boolean. Gets or sets the use system defaults formatting option. | Read/Write | Can be written only when formatting idle or active.
Value | Variant. Gets the field current value. | Read Only | Can be written only when formatting idle or active.
Width | Long. Gets or sets the object width, in twips. | Read/Write | Can be written only when formatting idle or active.
YearType | CRYearType. Gets or sets the year type. | Read/Write | Can be written only when formatting idle or active.
ZeroValueString | String. Gets or sets the zero value string for number field format. | Read/Write | Can be written only when formatting idle or active.


FieldObject Object Methods

The following methods are discussed in this section:

SetLineSpacing Method (FieldObject Object)

SetUnboundFieldSource Method (FieldObject Object)


SetLineSpacing Method (FieldObject Object)

Use SetLineSpacing method to get and set the line spacing and line spacing type.

Syntax
Sub SetLineSpacing (LineSpacing As Double,
    LineSpacingType As CRLineSpacingType)
Parameters

Parameter | Description
LineSpacing | Specifies the line spacing.
LineSpacingType | Specifies the line spacing type. Use one of CRLineSpacingType.


SetUnboundFieldSource Method (FieldObject Object)

Use SetUnbound FieldSource Method to bind a DataSource to an unbound field.

Syntax

Sub SetUnboundFieldSource (pUnboundFieldSource As String)

Parameter

Parameter | Description
pUnboundField Source | BSTR specifies the datasouce, Crystal formula format. See Remarks below.

Remarks

For example:

object.SetUnboundFieldSource("{Customer.CustomerID}")


FormattingInfo Object

The FormattingInfo object contains information about the section currently being formatted.

FormattingInfo Object Properties

Property | Description | Read/Write | Restriction in event handler
IsEndOfGroup | Boolean. Gets whether the current formatting section is the end of a group. | Read only | None
IsRepeatedGroup Header | Boolean. Gets whether the current formatting section is a repeated group header. | Read only | None
IsStartOfGroup | Boolean. Gets whether the current formatting section is the start of a group. | Read only | None


FormulaFieldDefinition Object

The FormulaFieldDefinition Object provides properties and methods for retrieving information and setting options for any named formula field in a report.

FormulaFieldDefinition Object Properties

Property | Description | Read/ Write | Restriction in event handler
FormulaField Name | String. Gets the formula field name as it appears in the RDC Dataview Panel. | Read only | None
Kind | CRFieldKind. Gets what kind of field (for example, database, summary, formula, etc.). | Read only | None
Name | String. Gets the unique name of the formula field in Crystal formula format as it would be referenced in the report (for example, {@ExampleFormula}). | Read only | None
NextValue | Variant. Gets the field next value. | Read only | Can be read only when top-level Report object is formatting active.
NumberOfBytes | Integer. Gets the number of bytes required to store the field data in memory. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None
PreviousValue | Variant. Gets the field previous value. | Read only | Can be read only when top-level Report object is formatting active.
Text | String. Gets or sets the text of the formula. The formula text is changed immediately in the report. If you generate a report with an invalid formula, you may receive an exception error. Syntax can be Crystal Refort or Visual Basic. See Remarks below. | Read/Write | Can be written only when formatting idle.
Value | Variant. Gets the field current value. | Read only | Can be read only when top-level Report object is formatting active.
ValueType | CRFieldValueType. Gets which type of value is found in the field. | Read only | None

Remarks

Crystal Reports 8.0 supports formulas in Crystal Reports syntax and Visual Basic syntax. When setting text to a formula, the syntax is determined by the FormulaSyntax property of the parent Report Object. The default syntax is Crystal Report syntax (crCrystalSyntaxFormula).


FormulaFieldDefinition Object Methods

The following methods are discussed in this section:

Check Method (FormulaFieldDefinition Object)


Check Method (FormulaFieldDefinition Object)

The Check method checks formula for errors (syntax errors).

Syntax

Sub Check (pBool As Boolean, ppErrorString As String)

Parameters

Parameter | Description
pBool | Boolean value indicating the condition of the formula string. Will be set to TRUE if the formula is valid and FALSE if the formula contains one or more errors.
ppErrorString | Specifies the error message string if the formula contains an error.


FormulaFieldDefinitions Collection

The FormulaFieldDefinitions Collection is a collection of named formulas in the report. Access a specific FormulaFieldDefinition Object, in the collection using the Item property.


FormulaFieldDefinitions Collection Properties

Property | Description | Read/ Write | Restriction in event handler
Count | Long. Gets the number of formula field definitions in the collection. | Read only | None
Item (index As Long) | FormulaFieldDefinitions Collection. Gets collection item. See Remarks below. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None

Remarks

Instead of using the Item property as shown, you can reference a formula field directly (for example, FormulaFieldDefinitions(1)).


FormulaFieldDefinitions Collection Methods

The following methods are discussed in this section:

Add Method (FormulaFieldDefinitions Collection)

Delete Method (FormulaFieldDefinitions Collection)


Add Method (FormulaFieldDefinitions Collection)

Use Add method to add the specified formula field to the FormulaFieldDefinitions Collection.

Syntax
Function Add (formulaName As String,

    Text As String) As FormulaFieldDefinition
Parameters

Parameter | Description
formulaName | Specifies the formula field that you want to add to the Collection.
Text | Specifies the text of the formula field that you want to add.

Returns

Returns a FormulaFieldDefinition member of the Collection.


Delete Method (FormulaFieldDefinitions Collection)

Use Delete method to remove the specified formula field from the FormulaFieldDefinitions Collection

Syntax

Sub Delete (index)

Parameter

Parameter | Description
index | Specifies the formula field that you want to delete from the Collection.


GraphObject Object

The GraphObject Object represents a graph/chart found in a report. This object provides properties for retrieving information and setting options for a graph in your report (that is, graph data type - group, detail or graph display type - bar, pie, etc.).

GraphObject Object Properties

Property | Description | Read/ Write | Restriction in event handler
AutoRangeData2Axis | Boolean. Gets or sets the auto range option for data2 axis. See Remarks below. | Read/Write | Can be written only when formatting idle.
AutoRangeDataAxis | Boolean. Gets or sets the auto range option for data axis. See Remarks below. | Read/Write | Can be written only when formatting idle.
BackColor | OLE_COLOR. Gets or sets the object background color. | Read/Write | Can be written only when formatting idle or active.
BarSize | CRBarSize. Gets or sets the bar size. | Read/Write | Can be written only when formatting idle.
BorderColor | OLE_COLOR. Gets or sets the object border color. | Read/Write | Can be written only when formatting idle or active.
BottomLineStyle | CRLineStyle. Gets or sets the bottom line style. | Read/Write | Can be written only when formatting idle or active.
CloseAt PageBreak | Boolean. Gets or sets the close border on page break option. | Read/Write | Can be written only when formatting idle or active.
Condition Fields | FieldDefinitions Collection. Gets the condition fields Collection. | Read only | None
CrossTab Object | CrossTabObject Object. Gets the crosstab object if this is a CrossTab chart. | Read only | None
Data2Axis Division Method | CRDivisionMethod. Gets or sets the data2 axis division method. | Read/Write | Can be written only when formatting idle.
Data2Axis Division Number | Long. Gets or sets the data2 axis division number. | Read/Write | Can be written only when formatting idle.
Data2AxisGridline | CRGridlineType. Gets or sets the data2 axis grid line type. | Read/Write | Can be written only when formatting idle.
Data2Axis Number Format | CRNumberFormat. Gets or sets the data2 axis number format. | Read/Write | Can be written only when formatting idle.
DataAxis Division Method | CRDivisionMethod. Gets or sets the data axis division method. | Read/Write | Can be written only when formatting idle.
DataAxis Division Number | Long. Gets or sets the data axis division number. | Read/Write | Can be written only when formatting idle.
DataAxis Gridline | CRGridlineType. Gets or sets the data axis grid line type. | Read/Write | Can be written only when formatting idle.
DataAxis Number Format | CRNumberFormat. Gets or sets the data axis number format. | Read/Write | Can be written only when formatting idle.
DataLabel Font | IFontDisp. Gets or sets standard OLE font for chart data labels. | Read/Write | Can be written only when formatting idle.
DataPoint | CRGraphDataPoint. Gets or sets the graph data points on risers. | Read/Write | Can be written only when formatting idle.
DataTitle Font | IFontDisp. Gets or sets standard OLE font for chart data title. | Read/Write | Can be written only when formatting idle.
DataType | CRGraphDataType. Returns which type of data used in the graph. | Read only | None
DataValueNumber Format | CRNumberFormat. Gets or sets the data value number format. | Read/Write | Can be written only when formatting idle.
EnableAutoScale DataAxis | Boolean. Gets or sets the data axis auto-scale option. | Read/Write | Can be written only when formatting idle.
EnableAutoScale Data2Axis | Boolean. Gets or sets the data2 axis auto-scale option. | Read/Write | Can be written only when formatting idle.
EnableFor EachRecord | Boolean. Gets or sets the enable for each record option. | Read/Write | Can be written only when formatting idle.
EnableShowLegend | Boolean. Gets or sets the show legend option. | Read/Write | Can be written only when formatting idle.
Enable Summarize Values | Boolean. Gets or sets the enable summarize values option. | Read/Write | Can be written only when formatting idle.
FootNote | String. Gets or sets the footnote. | Read/Write | Can be written only when formatting idle.
Footnote Font | IFontDisp. Gets or sets standard OLE font for chart footnote. | Read/Write | Can be written only when formatting idle.
GraphColor | crgraphcolor. Gets or sets the graph color. | Read/Write | Can be written only when formatting idle.
Graph Direction | CRGraphDirection. Gets or sets the graph direction. | Read/Write | Can be written only when formatting idle.
GraphType | CRGraphType. Gets or sets the graph type. | Read/Write | Can be written only when formatting idle.
GroupAxisGridline | CRGridlineType. Gets or sets the group axis grid line type. | Read/Write | Can be written only when formatting idle.
GroupLabelFont | IFontDisp. Gets or sets standard OLE font for chart group labels. | Read/Write | Can be written only when formatting idle.
GroupsTitle | String. Gets or sets the groups title. | Read/Write | Can be written only when formatting idle.
GroupTitleFont | IFontDisp. Gets or sets standard OLE font for chart group title. | Read/Write | Can be written only when formatting idle.
HasDropShadow | Boolean. Gets or sets the border drop shadow option. | Read/Write | Can be written only when formatting idle or active.
Height | Long. Gets or sets the object height, in twips. | Read/Write | Can be written only when formatting idle or active.
IsFootnote ByDefault | Boolean. Gets or sets footnote default flag. | Read/Write | Can be written only when formatting idle or active.
IsGroups TitleBy Default | Boolean. Gets or set groups title default flag. | Read/Write | Can be written only when formatting idle or active.
IsSeriesTitleByDefault | Boolean. Gets or sets series title default flag. | Read/Write | Can be written only when formatting idle or active.
IsSubTitle ByDefault | Boolean. Get or sets subtitle default flag. | Read/Write | Can be written only when formatting idle or active.
IsTitleBy Default | Boolean. Gets or sets title default flag. | Read/Write | Can be written only when formatting idle or active.
Keep Together | Boolean. Gets or sets keep object together option. | Read/Write | Can be written only when formatting idle or active.
Kind | CRObjectKind. Gets which kind of object (for example, box, cross-tab, etc.). | Read only | None
Left | Long. Gets or sets the object upper left position, in twips. | Read/Write | Can be written only when formatting idle or active.
LeftLine Style | CRLineStyle. Gets or sets the left line style. | Read/Write | Can be written only when formatting idle or active.
LegendFont | IFontDisp. Gets or sets standard OLE font for legend. | Read/Write | Can be written only when formatting idle.
Legend Layout | CRPieLegendLayout. Gets or sets the legend layout for a pie chart. | Read/Write | Can be written only when formatting idle.
Legend Position | CRLegendPosition. Gets or sets the legend position. | Read/Write | Can be written only when formatting idle.
Marker Shape | CRMarkerShape. Gets or sets the marker shape. | Read/Write | Can be written only when formatting idle.
MarkerSize | CRMarkerSize. Gets or sets the marker size. | Read/Write | Can be written only when formatting idle.
MaxData2 AxisValue | Double. Gets or sets data2-axis max value. See Remarks below. | Read/Write | Can be written only when formatting idle.
MaxData AxisValue | Double. Gets or sets data-axis max value. See Remarks below. | Read/Write | Can be written only when formatting idle.
MinData2 AxisValue | Double. Gets or sets data2-axis min value. See Remarks below. | Read/Write | Can be written only when formatting idle.
MinData AxisValue | Double. Gets or sets data-axis min value. See Remarks below. | Read/Write | Can be written only when formatting idle.
Name | String. Gets or sets the object name. | Read/Write | Can be written only when formatting idle.
Parent | Section Object. Gets reference to the parent object. | Read only | None
PieSize | CRPieSize. Gets or sets the size for pie charts. | Read/Write | Can be written only when formatting idle.
RightLine Style | CRLineStyle. Gets or sets the right line style. | Read/Write | Can be written only when formatting idle or active.
SeriesAxisGridline | CRGridlineType. Gets or sets the series axis grid line type. | Read/Write | Can be written only when formatting idle.
SeriesLabelFont | IFontDisp. Gets or sets standard OLE font for chart series labels. | Read/Write | Can be written only when formatting idle.
SeriesTitle | String. Gets or sets the series title. | Read/Write | Can be written only when formatting idle.
SeriesTitle Font | IFontDisp. Gets or sets standard OLE font for chart series title. | Read/Write | Can be written only when formatting idle.
SliceDetachment | CRSliceDetachment. Gets or sets the slice detachment. | Read/Write | Can be written only when formatting idle.
SubTitle | String. Gets or sets subtitle. | Read/Write | Can be written only when formatting idle.
SubTitle Font | IFontDisp. Gets or sets standard OLE font for chart subtitle. | Read/Write | Can be written only when formatting idle.
Summary Fields | SummaryFieldDefinitions Collection. Gets the summary fields Collection. | Read only | None
Suppress | Boolean. Gets or sets the object visibility. | Read/Write | Can be written only when formatting idle or active.
Title | String. Gets or sets the title. | Read/Write | Can be written only when formatting idle.
TitleFont | IFontDisp. Gets or sets standard OLE font for chart title. | Read/Write | Can be written only when formatting idle.
Top | Long. Gets or sets the object upper top position, in twips. | Read/Write | Can be written only when formatting idle or active.
TopLine Style | CRLineStyle. Gets or sets the top line style. | Read/Write | Can be written only when formatting idle or active.
Viewing Angle | CRViewingAngle. Gets or sets the viewing angle. | Read/Write | Can be written only when formatting idle.
Width | Long. Gets or sets the object width, in twips. | Read/Write | Can be written only when formatting idle or active.

Remarks

Properties Max/MinData/SeriesAxisValue will be ignored if the corresponding AutoRangeData/SeriesAxis property is set to TRUE. If the Max/MinDataDataAxis/Series properties are set at runtime, then the corresponding AutoRangeData/SeriesAxis must be set to FALSE.

This property must be set to FALSE... | ...or this property will be ignored
AutoRangeData2Axis | MaxData2AxisValue
AutoRangeDataAxis | MaxDataAxisValue
AutoRangeData2Axis | MinData2AxisValue
AutoRangeDataAxis | MinDataAxisValue


GroupNameFieldDefinition Object

The GroupNameFieldDefinition Object provides properties and methods for retrieving information on a group name field found in a report (for example, number of group, value type, etc.). A GroupNameFieldDefinition Object can be obtained from the Field property of the FieldObject Object when the specified field is a group name field or from a GroupNameFieldDefinitions Collection retrieved from the GroupNameFields property of the Report Object.

GroupNameFieldDefinition Object Properties

Property | Description | Read/ Write | Restriction in event handler
GroupNameField Name | String. Gets the group name field name. | Read only | None
GroupNumber | Integer. If the area is a group, this gets the group number. Otherwise, exception is thrown. | Read only | None
Kind | CRFieldKind. Gets which kind of field (for example, database, summary, formula, etc.). | Read only | None
Name | String. Gets the field definition unique formula name in Crystal Report formula syntax. | Read only | None
NextValue | Variant. Gets the field next value. | Read only | Can be read only when top-level Report object is formatting active.
NumberOfBytes | Integer. Gets the number of bytes required to store the field data in memory. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None
PreviousValue | Variant. Gets the field previous value. | Read only | Can be read only when top-level Report object is formatting active.
Value | Variant. Gets the field current value. | Read only | Can be read only when top-level Report object is formatting active.
ValueType | CRFieldValueType. Gets which type of value is found in the field. | Read only | None


GroupNameFieldDefinitions Collection

The GroupNameFieldDefinitions Collection is a collection of named groups in the report. Access a specific GroupNameFieldDefinition Object in the collection using the Item property.

GroupNameFieldDefinitions Collection Properties

Property | Description | Read/Write | Restriction in event handler
Count | Long. Gets the number of group name field definitions in the Collection. | Read only | None
Item (index As Long) | GroupNameFieldDefinition Object. Gets the specified object from the Collection. Item has an index parameter that is the 1-based index number of the Object in the Collection. The items in the collection are indexed in the order they were added to the report. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None

Remarks

Instead of using the Item property as shown, you can reference a group name field directly (for example, GroupNameFieldDefinitions(1)).


FieldDefinition Object

The IFieldDefinition Object provides generic properties for the various types of field definition objects.

FieldDefinition Object Properties

Property | Description | Read/ Write | Restriction in event handler
Kind | CRFieldKind. Gets field definition kind. | Read only | None
Name | String. Gets field definition unique formula name. | Read only | None
NextValue | Variant. Gets the field next value. | Read only | None
NumberOfBytes | Integer. Gets field number of bytes. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None
PreviousValue | Variant. Gets the field previous value. | Read only | None
UseCount | Long. Gets the field use count. | Read only | None
Value | Variant. Gets the field current value. | Read only | None
ValueType | CRFieldValueType. Gets the field value type. | Read only | None


IReportObject

The IReportObject Object provides generic properties for the various types of report objects.

ReportObject Properties

Property | Description | Read/ Write | Restriction in event handler
BackColor | OLE_COLOR. Gets or sets the object background color. | Read/Write | Can be written only when formatting idle or active.
BorderColor | OLE_COLOR. Gets or sets the object border color. | Read/Write | Can be written only when formatting idle or active.
BottomLineStyle | CRLineStyle. Gets or sets bottom line style. | Read/Write | Can be written only when formatting idle or active.
CloseAtPageBreak | Boolean. Gets or sets the close border on page break option. | Read/Write | Can be written only when formatting idle or active.
EnableTight Horizontal | Boolean. Gets or sets the enable tight horizontal option. | Read/Write | Can be written only when formatting idle or active.
HasDropShadow | Boolean. Gets or sets the border drop shadow option. | Read/Write | Can be written only when formatting idle or active.
Height | Long. Gets or sets object height, in twips. | Read/Write | Can be written only when formatting idle or active.
KeepTogether | Boolean. Gets or sets the keep object together option. | Read/Write | Can be written only when formatting idle or active.
Kind | CRObjectKind. Gets which kind of object (for example, box, cross-tab, field, etc.). | Read only | None
Left | Long. Gets or sets the object upper left position, in twips. | Read/Write | Can be written only when formatting idle or active.
LeftLineStyle | CRLineStyle. Gets or sets the left line style. | Read/Write | Can be written only when formatting idle or active.
Name | String. Gets or sets the object name. | Read/Write | Can be written only when formatting idle or active.
Parent | Section Object. Reference to the parent object. | Read only | Can be written only when formatting idle or active.
RightLineStyle | CRLineStyle. Gets or sets the right line style. | Read/Write | Can be written only when formatting idle or active.
Suppress | Boolean. Gets or sets the object visibility. | Read/Write | Can be written only when formatting idle or active.
Top | Long. Gets or sets the object upper top position, in twips. | Read/Write | Can be written only when formatting idle or active.
TopLineStyle | CRLineStyle. Gets or sets the top line style. | Read/Write | Can be written only when formatting idle or active.
Width | Long. Gets or sets the object width, in twips. | Read/Write | Can be written only when formatting idle or active.


LineObject Object

The LineObject Object represents a line drawn on a report. This object provides properties for getting information for lines on a report.

LineObject Object Properties

Property | Description | Read/Write | Restriction in event handler
Bottom | Long. Gets or sets the line lower bottom position, in twips. | Read/Write | Can be written only when formatting idle.
EndSection | Section Object. Gets the end section. | Read only | None
ExtendToBottom OfSection | Boolean. Gets or sets the extend to bottom of section option. | Read/Write | Can be written only when formatting idle.
Kind | CRObjectKind. Gets which kind of object (for example, box, cross-tab, field, etc.). | Read only | None
Left | Long. Gets or sets the object upper left position, in twips. | Read/Write | Can be written only when formatting idle.
LineColor | OLE_COLOR. Gets or sets the line color. | Read/Write | Can be written only when formatting idle.
LineStyle | CRLineStyle. Gets or sets the line style. See Remarks below. | Read/Write | Can be written only when formatting idle.
LineThickness | Long. Gets or sets the line thickness, in twips. | Read/Write | Can be written only when formatting idle.
Name | String. Gets or sets object name. | Read/Write | Can be written only when formatting idle.
Parent | Section Object. Gets reference to the parent object. | Read only | None
Right | Long. Gets or sets the line lower right position, in twips. | Read/Write | Can be written only when formatting idle.
Suppress | Boolean. Gets or sets the object visibility. | Read/Write | Can be written only when formatting idle.
Top | Long. Gets or sets the object upper top position, in twips. | Read/Write | Can be written only when formatting idle.

Remarks

For property LineStyle, crLSDoubleLine and crLSNoLine are not valid.


MapObject Object

The MapObject Object represents a geographic map object in a report. This object provides properties for getting information for Map objects in a report.

MapObject Object Properties

Property | Description | Read/ Write | Restriction in event handler
BackColor | OLE_COLOR. Gets or sets the object background color. | Read/Write | Can be written only when formatting idle or active.
BorderColor | OLE_COLOR. Gets or sets the object border color. | Read/Write | Can be written only when formatting idle or active.
BottomLine Style | CRLineStyle. Gets or sets the bottom line style. | Read/Write | Can be written only when formatting idle or active.
CloseAtPage Break | Boolean. Gets or sets the close border on page break option. | Read/Write | Can be written only when formatting idle or active.
HasDrop Shadow | Boolean. Gets or sets the border drop shadow option. | Read/Write | Can be written only when formatting idle or active.
Height | Long. Gets or sets the object height, in twips. | Read/Write | Can be written only when formatting idle or active.
KeepTogether | Boolean. Gets or sets the keep object together option. | Read/Write | Can be written only when formatting idle or active.
Kind | CRObjectKind. Gets which kind of object (for example, box, cross-tab, field, etc.). | Read only | None
Left | Long. Gets or sets the object upper left position, in twips. | Read/Write | Can be written only when formatting idle or active.
LeftLineStyle | CRLineStyle. Gets or sets the left line style. | Read/Write | Can be written only when formatting idle or active.
Name | String. Gets or sets the object name. | Read/Write | Can be written only when formatting idle.
Parent | Section Object. Gets reference to the parent object. | Read only | None
RightLineStyle | CRLineStyle. Gets or sets the right line style. | Read/Write | Can be written only when formatting idle or active.
Suppress | Boolean. Gets or sets the object visibility. | Read/Write | Can be written only when formatting idle or active.
Top | Long. Gets or sets the object upper top position, in twips. | Read/Write | Can be written only when formatting idle or active.
TopLineStyle | CRLineStyle. Gets or sets the top line style. | Read/Write | Can be written only when formatting idle or active.
Width | Long. Gets or sets the object width, in twips. | Read/Write | Can be written only when formatting idle or active.


ObjectSummaryFieldDefinitions Collection

ObjectSummaryFieldDefinitions is a Collection of SummaryFieldDefinition Object Objects.

ObjectSummaryFieldDefinitions Collection Properties

Property | Description | Read/Write | Restriction in event handler
Count | Long. Gets the number of object summary field definitions in the Collection. | Read only | None
Item (index As Long) | SummaryFieldDefinition Object. Gets the specified object from the Collection. Item has an index parameter that is the 1-based index number of the Object in the Collection. The items in the collection are indexed in the order they were added to the report. | Read only | None
Parent | IReportObject. Gets reference to the parent object. | Read only | None


ObjectSummaryFieldDefinitions Collection Methods

The following methods are discussed in this section:

Add Method (ObjectSummaryFieldDefinitions Collection)

Delete Method (ObjectSummaryFieldDefinitions Collection)


Add Method (ObjectSummaryFieldDefinitions Collection)

Use Add method to add the specified object summary field to the ObjectSummaryFieldDefinitions Collection.

Syntax

Sub Add (summaryField)

Parameter

Parameter | Description
summaryField | Specifies the object summary field that you want to add to the Collection.


Delete Method (ObjectSummaryFieldDefinitions Collection)

Use Delete method to remove the specified object summary field from the ObjectSummaryFieldDefinitions Collection.

Syntax

Sub Delete (index As Long)

Parameter

Parameter | Description
index | Specifies the object summary field that you want to delete from the Collection.


OlapGridObject Object

The OlapGridObject Object represents an Olap Object in a report.

OlapGridObject Object Properties

Property | Description | Read/ Write | Restriction in event handler
BackColor | OLE_COLOR. Gets or sets the object background color. | Read/Write | Can be written only when formatting idle or active.
BorderColor | OLE_COLOR. Gets or sets the object border color. | Read/Write | Can be written only when formatting idle or active.
BottomLineStyle | CRLineStyle. Gets or sets the bottom line style. | Read/Write | Can be written only when formatting idle or active.
CloseAtPageBreak | Boolean. Gets or sets the close border on page break option. | Read/Write | Can be written only when formatting idle or active.
HasDropShadow | Boolean. Gets or sets the border drop shadow option. | Read/Write | Can be written only when formatting idle or active.
Height | Long. Gets the object height, in twips. | Read only | Can be written only when formatting idle or active.
KeepTogether | Boolean. Gets or sets the keep object together option. | Read/Write | Can be written only when formatting idle or active.
Kind | CRObjectKind. Gets report object kind. | Read only | None
Left | Long. Gets or sets the object upper left position, in twips. | Read/Write | Can be written only when formatting idle or active.
LeftLineStyle | CRLineStyle. Gets or sets the left line style. | Read/Write | Can be written only when formatting idle or active.
Name | String. Gets or sets the object name. | Read/Write | Can be written only when formatting idle or active.
Parent | Section Object. Gets reference to the parent object. | Read only | None
RightLineStyle | CRLineStyle. Gets or sets the right line style. | Read/Write | Can be written only when formatting idle or active.
Suppress | Boolean. Gets or sets the object visibility. | Read/Write | Can be written only when formatting idle or active.
Top | Long. Gets or sets the object upper top position, in twips. | Read/Write | Can be written only when formatting idle or active.
TopLineStyle | CRLineStyle. Gets or sets the top line style. | Read/Write | Can be written only when formatting idle or active.
Width | Long. Gets the object width, in twips. | Read only | Can be written only when formatting idle or active.


OleObject Object

The OleObject Object represents an OLE object in a report. This object provides properties for getting information for OLE objects in a report.

OleObject Object Properties

Property | Description | Read/ Write | Restriction in event handler
BackColor | OLE_COLOR. Gets or sets the object background color. | Read/Write | Can be written only when formatting idle or active.
BorderColor | OLE_COLOR. Gets or sets the object border color. | Read/Write | Can be written only when formatting idle or active.
Bottom Cropping | Long. Gets or sets the bottom cropping size, in twips. | Read/Write | Can be written only when formatting idle.
BottomLine Style | CRLineStyle. Gets or sets the bottom line style. | Read/Write | Can be written only when formatting idle or active.
CloseAtPage Break | Boolean. Gets or sets the close border on page break option. | Read/Write | Can be written only when formatting idle or active.
Formatted Picture | IPictureDisp. Gets or sets the specified picture during formatting. | Read/Write | Can be read or written only when top-level Report object is formatting active.
HasDrop Shadow | Boolean. Gets or sets the border drop shadow option. | Read/Write | Can be written only when formatting idle or active.
Height | Long. Gets or sets the object height, in twips. | Read/Write | Can be written only when formatting idle or active.
KeepTogether | Boolean. Gets or sets the keep object together option. | Read/Write | Can be written only when formatting idle or active.
Kind | CRObjectKind. Gets which kind of object (for example, box, cross-tab, field, etc.). | Read only | None
Left | Long. Gets or sets the object upper left position, in twips. | Read/Write | Can be written only when formatting idle or active.
LeftCropping | Long. Gets or sets the left cropping size, in twips. | Read/Write | Can be written only when formatting idle.
LeftLineStyle | CRLineStyle. Gets or sets the left line style. | Read/Write | Can be written only when formatting idle or active.
Name | String. Gets or sets the object name. | Read/Write | Can be written only when formatting idle.
Parent | Section Object. Gets reference to the parent object. | Read only | None
RightCropping | Long. Gets or sets the right cropping size, in twips. | Read/Write | Can be written only when formatting idle.
RightLineStyle | CRLineStyle. Gets or sets the right line style. | Read/Write | Can be written only when formatting idle or active.
Suppress | Boolean. Gets or sets the object visibility. | Read/Write | Can be written only when formatting idle or active.
Top | Long. Gets or sets the object upper top position, in twips. | Read/Write | Can be written only when formatting idle or active.
TopCropping | Long. Gets or sets the top cropping size, in twips. | Read/Write | Can be written only when formatting idle.
TopLineStyle | CRLineStyle. Gets or sets the top line style. | Read/Write | Can be written only when formatting idle or active.
Width | Long. Gets or sets the object width, in twips. | Read/Write | Can be written only when formatting idle or active.
XScaling | Double. Gets or sets the width scaling factor. For example, 1 means 100%, 2 means 200%, 0.5 means 50% etc. The scaling factor may range from 0.01 to 100. | Read/Write | Can be written only when formatting idle.
YScaling | Double. Gets or sets height scaling factor. For example, 1 means 100%, 2 means 200%, 0.5 means 50% etc. The scaling factor may range from 0.01 to 100. | Read/Write | Can be written only when formatting idle.


OleObject Object Methods

The following methods are discussed in this section:

SetOleLocation Method (OleObject Object)


SetOleLocation Method (OleObject Object)

Use SetOleLocation method to specify the location of an OLE Object.

Syntax

Sub SetOleLocation (pLocation As String)

Parameter

Parameter | Description
pLocation | Specifies the location of the OLE Object.

Remarks

SetOleLocation must be called from the Format Event of the Section object, and only when formatting active. For more more information see Format Event (Section Object).


Page Object

The Page Object is part of the Page Engine. Use the Page Engine when designing web sites using Active Server Pages, the Crystal Report Engine Automation Server, and the Crystal Design-Time ActiveX Control. Unless you are experienced with the Crystal Report Engine Object Library, you should allow the Crystal Design-Time ActiveX Control to generate VBScript code in your Active Server Pages that controls the Page Engine objects.

The Page Engine generates pages of a report on the web server and sends the pages to client web browsers as they are requested. For example, when a user first requests a report, only the first page is sent to the web browser. If the user pages forward or backward in the report, or requests a specific page, only that page is sent. This limits the resources required by the web server and reduces download time for the client browser. A Page Object is a single generated page that is sent to the browser.

Page Object Properties

Property | Description | Read/Write | Restriction in event handler
IsLastPage | Boolean. Gets whether the page generated is the last page of the report. | Read only | None
IsMissing TotalPageCount | Boolean. Gets whether the page misses the total page count. | Read only | None
PageNumber | Long. Gets the page number. | Read only | None
Parent | PageGenerator Object. Gets reference to the parent object. | Read only | None


Page Object Methods

The following methods are discussed in this section:

RenderEPF Method (Page Object)

RenderHTML Method (Page Object)


RenderEPF Method (Page Object)

The RenderEPF method returns a variant that contains EPF data for the report page. This method can be invoked only when in formatting idle mode.

Syntax

Function RenderEPF (resultType As CRRenderResultType)

Parameter

Parameter | Description
ResultType | CRRenderResultType. Specifies whether the page will be rendered using strings or arrays. See Remarks below.

Returns

Returns the EPF stream.

Remarks

Currently only arrays are supported.


RenderHTML Method (Page Object)

The RenderHTML method returns a variant that contains HTML data for the report page. This method can be invoked only when in formatting idle mode.

Syntax
Function RenderHTML (includeDrillDownLinks As Boolean,

    pageStyle As CRHTMLPageStyle, toolbarStyle As CRHTMLToolbarStyle,

    baseURL As String, resultType As CRRenderResultType)
Parameters

Parameter | Description
includeDrillDown Links | Indicates whether or not the HTML page will include hyperlinks for drilling-down on summary data.
pageStyle | CRHTMLPageStyle. Specifies the style of the HTML page to be rendered.
toolbarStyle | CRHTMLToolbarStyle. Bitwise constant specifies the style of the toolbar to be used. Constants can be XOR'd.
baseURL | The URL used to access the report when it is first generated.
resultType | CRRenderResultType. Specifies whether the page will be rendered using strings or arrays. See Remarks below.

Returns

Returns the HTML stream.

Remarks

Currently only arrays are supported.


PageEngine Object

Use the PageEngine object when designing web sites using Active Server Pages, the Crystal Report Engine Automation Server, and the Crystal Design-Time ActiveX Control. Unless you are experienced with the Crystal Report Engine Object Library, you should allow the Crystal Design-Time ActiveX Control to generate VBScript code in your Active Server Pages that controls the Page Engine objects.

The Page Engine generates pages of a report on the web server and sends the pages to client web browsers as they are requested. For example, when a user first requests a report, only the first page is sent to the web browser. If the user pages forward or backward in the report, or requests a specific page, only that page is sent. This limits the resources required by the web server and reduces download time for the client browser.

PageEngine Object Properties

Property | Description | Read/ Write | Restriction in event handler
ImageOptions | CRImageType. Gets or sets the image type for EPF format. | Read/Write | Can be written only when formatting idle.
Parent | Report Object. Gets reference to the parent object. | Read only | None
PlaceHolder Options | CRPlaceHolderType. Gets or sets the EPF place holder options. | Read/Write | Can be written only when formatting idle.
ValueFormat Options | CRValueFormatType. Gets or sets the EPF value format options. | Read/Write | Can be written only when formatting idle.


PageEngine Object Methods

The following methods are discussed in this section:

CreatePageGenerator Method (PageEngine Object)

RenderTotallerETF Method (PageEngine Object)

RenderTotallerHTML Method (PageEngine Object)


CreatePageGenerator Method (PageEngine Object)

The CreatePageGenerator method returns a PageGenerator Object, allowing you to get pages from the view of the report, specified by the GroupPath parameter. This method can be invoked only when in formatting idle mode.

Syntax

Function CreatePageGenerator (GroupPath, [DrillDownLevel]) As PageGenerator

Parameter

Parameter | Description
GroupPath | Specifies an integer array that represents the group path. An empty array would represent the entire report, an array (0, 1) would represent a drill down on the second group member within the first group member where 0 = first group in Group #1 and 1 = second group in Group #2.
[DrillDownLevel] | Reserved. Do not use.

Returns

Returns a PageGenerator Object.


RenderTotallerETF Method (PageEngine Object)

The RenderTotallerETF method returns a variant that contains ETF data for the Group Tree. This method can be invoked only when in formatting idle mode.

Syntax
Function RenderTotallerETF (rootGroupPath, startingChildNumber As Long,

    pastRootLevels As Integer, maxNodeCount,

    resultType As CRRenderResultType)
Parameters

Parameter | Description
rootGroupPath | Specifies an integer array that represents the group path. An empty array would represent the entire report, an array (0, 1) would represent a drill down on the second group member within the first group member where 0 = first group in Group #1 and 1 = second group in Group #2.
startingChildNumber | The start child number to display.
pastRootLevels | Past root levels.
maxNodeCount | The maximum number of nodes for each group level in the Group Tree.
resultType | CRRenderResultType. Specifies whether the page will be rendered using strings or arrays. See Remarks below.

Returns

Returns the Totaller ETF stream.

Remarks

Currently only arrays are supported.


RenderTotallerHTML Method (PageEngine Object)

The RenderTotallerHTML method returns a variant that contains HTML data for the Group Tree. This method can be invoked only when in formatting idle mode.

Syntax
Function RenderTotallerHTML (rootGroupPath, startingChildNumber As Long,
    pastRootLevels As Integer, maxNodeCount, openGroupPath,

    includeDrillDownLinks As Boolean, baseURL As String,

    resultType As CRRenderResultType)
Parameters

Parameter | Description
rootGroupPath | Specifies the base URL string.
startingChildNumber | The start child number to display.
pastRootLevels | A value indicating the number of past root levels.
maxNodeCount | The maximum number of nodes to display for each group level in the Group Tree.
openGroupPath | An array of groups to be opened in the report.
includeDrillDownLinks | Indicates whether or not drill down hyperlinks are generated for summary values in the report.
baseURL | The URL used to access the report when it is first generated.
resultType | CRRenderResultType. Specifies whether the page will be rendered using strings or arrays. See Remarks below.

Returns

Returns the HTML stream.

Remarks

Currently only arrays are supported.


PageGenerator Object

The PageGenerator Object is part of the Page Engine. Use the Page Engine when designing web sites using Active Server Pages, the Crystal Report Engine Automation Server, and the Crystal Design-Time ActiveX Control. Unless you are experienced with the Crystal Report Engine Object Library, you should allow the Crystal Design-Time ActiveX Control to generate VBScript code in your Active Server Pages that controls the Page Engine objects.

The Page Engine generates pages of a report on the web server and sends the pages to client web browsers as they are requested. For example, when a user first requests a report, only the first page is sent to the web browser. If the user pages forward or backward in the report, or requests a specific page, only that page is sent. This limits the resources required by the web server and reduces download time for the client browser. A PageGenerator object generates Page Object, as they are requested and allows options for manipulating the report as a whole.

PageGenerator Object Properties

Property | Description | Read/ Write | Restriction in event handler
ContainingGroup Name | String. Gets containing group name for out of place subreport view. | Read only | None
ContainingGroup Path | Variant. Gets containing group path for out of place subreport view. | Read only | None
ContainingPage Number | Long. Gets containing page number for out of place subreport view. | Read only | None
DrillDownLevel | Ignore. This property is currently reserved. | Read only | None
GroupName | String. Gets the group name for drill down on graph view. | Read only | None
GroupPath | Variant. Gets the GroupPath parameter set by CreatePageGenerator Method (PageEngine Object). | Read only | None
Pages | Pages Collection. Gets the collection of pages for a specified view. | Read only | None
Parent | PageEngine Object. Gets reference to the parent object. | Read only | None
ReportName | String. Gets the report name for drill down on out of place subreport view. | Read only | None
xOffset | Long. Gets the object x-offset. | Read only | None
yOffset | Long. Gets the object y-offset. | Read only | None


PageGenerator Object Methods

The following methods are discussed in this section:

CreateSubreportPageGenerator Method (PageGenerator Object).

DrillOnGraph Method (PageGenerator Object).

DrillOnMap Method (PageGenerator Object).

DrillOnSubreport Method (PageGenerator Object).

Export Method (PageGenerator Object).

FindText Method (PageGenerator Object).

GetPageNumberForGroup Method (PageGenerator Object).

RenderTotallerETF Method (PageGenerator Object).

RenderTotallerHTML Method (PageGenerator Object).


CreateSubreportPageGenerator Method (PageGenerator Object)

Use CreateSubreportPageGenerator method to create a page generator that contains the subreport view context.

Syntax
Function CreateSubreportPageGenerator (GroupPath, [DrillDownLevel]

    ) As PageGenerator
Parameters

Parameter | Description
GroupPath | Specifies an integer array that represents the group path. An empty array would represent the entire report, an array (0, 1) would represent a drill down on the second group member within the first group memberwhere 0 = first group in Group #1 and 1 = second group in Group #2.
[DrillDownLevel] | Reserved. Do not use.


DrillOnGraph Method (PageGenerator Object)

The DrillOnGraph method creates a new PageGenerator Object that results from drilling down on the specified point in a graph on the given page. This method can be invoked only when in formatting idle mode.

Syntax
Function DrillOnGraph (PageNumber As Long, xOffset As Long, yOffset As
Long

    ) As PageGenerator
Parameters

Parameter | Description
PageNumber | Specifies the page number.
xOffset | Specifies the X coordinate on page, in twips, where the drill down occurred.
yYOffset | Specifies the Y coordinate on page, in twips, where the drill down occurred.

Returns

Returns a PageGenerator Object.


DrillOnMap Method (PageGenerator Object)

The DrillOnMap method creates a newPageGenerator Object, that results from drilling down on the specified point in a map on the given page. This method can be invoked only when in formatting idle mode.

Syntax
Function DrillOnMap (PageNumber As Long, xOffset As Long, yOffset As Long
    ) As PageGenerator
Parameters

Parameter | Description
PageNumber | Specifies the page number.
xOffset | Specifies the X coordinate on page, in twips, where the drill down occurred.
yOffset | Specifies the Y coordinate on page, in twips, where the drill down occurred.

Returns

Returns a PageGenerator Object.


DrillOnSubreport Method (PageGenerator Object)

The DrillOnSubreport method creates a new PageGenerator Object, that results from drilling down on the specified point in a real-time subreport on the given page. This method can be invoked only when in formatting idle mode.

Syntax
Function DrillOnSubreport (PageNumber As Long, xOffset As Long,

    yOffset As Long) As PageGenerator
Parameters

Parameter | Description
PageNumber | Specifies the page number.
xOffset | Specifies the X coordinate on page, in twips, where the drill down occurred.
yOffset | Specifies the Y coordinate on page, in twips, where the drill down occurred.

Returns

Returns a PageGenerator Object.


Export Method (PageGenerator Object)

Use Export method to obtain an export stream.

Syntax

Function Export (resultType As CRRenderResultType)

Parameter

Parameter | Description
resultType | CRRenderResultType. Sepcifies the result type.

Returns

Returns the export data stream.


FindText Method (PageGenerator Object)

Use FindText method to search for a text string in the specified direction starting on the specified page in the current drill down view.

Syntax
Function FindText (Text As String, direction As CRSearchDirection,

    pPageNumber) As Boolean
Parameters

Parameter | Description
Text | Specifies the text string that you want to search for.
direction | CRSearchDirection. Specifies the direction that you want to search.
pPageNumber | Specifies the page on which you want to start the search.

Returns
  • TRUE if the specified text string is found.
  • FALSE if the specified text string is not found.


GetPageNumberForGroup Method (PageGenerator Object)

The GetPageNumberForGroup method returns the page number on which the specified group starts. This method can be invoked only when in formatting idle mode.

Syntax

Function GetPageNumberForGroup (GroupPath) As Long

Parameters

Parameter | Description
GroupPath | Specifies an integer array that represents the group path. An empty array would represent the entire report, an array (0, 1) would represent a drill down on the second group member within the first group memberwhere 0 = first group in Group #1 and 1 = second group in Group #2.

Returns

Returns the page number on which the specified group starts.


RenderTotallerETF Method (PageGenerator Object)

The RenderTotallerETF method returns a variant that contains ETF data for the Group Tree. This method can be invoked only when in formatting idle mode.

Syntax
Function RenderTotallerETF (rootGroupPath, startingChildNumber As Long,

    pastRootLevels As Integer, maxNodeCount,

    resultType As CRRenderResultType)
Parameters

Parameter | Description
rootGroupPath | Specifies an integer array that represents the root group path. An empty array would represent the entire report, an array (0, 1) would represent a drill down on the second group member within the first group member where 0 = first group in Group #1 and 1 = second group in Group #2.
startingChildNumber | The starting child level to display the report grouping at.
pastRootLevels | Specifies the number of past root levels.
maxNodeCount | The maximum number of nodes for each group level in the Group Tree.
resultType | CRRenderResultType. Specifies whether the page will be rendered using strings or arrays. See Remarks below.

Returns

Returns the Totaller ETF stream.

Remarks

Currently only arrays are supported.


RenderTotallerHTML Method (PageGenerator Object)

The RenderTotallerHTML method returns a variant that contains HTML data for the Group Tree. This method can be invoked only when in formatting idle mode.

Syntax
Function RenderTotallerHTML (rootGroupPath, startingChildNumber As Long,
    pastRootLevels As Integer, maxNodeCount, openGroupPath,

    includeDrillDownLinks As Boolean, baseURL As String,

    resultType As CRRenderResultType)
Parameters

Parameter | Description
rootGroupPath | Specifies an integer array that represents the root group path. An empty array would represent the entire report, an array (0, 1) would represent a drill down on the second group member within the first group member where 0 = first group in Group #1 and 1 = second group in Group #2.
startingChild Number | The starting child level to display the report grouping at.
pastRootLevels | A value indicating the number of past root levels.
maxNodeCount | The maximum number of nodes to display for each group level in the Group Tree.
openGroupPath | An array of groups to be opened in the report.
includeDrill DownLinks | Indicates whether or not drill down hyperlinks are generated for summary values in the report.
baseURL | The URL used to access the report when it is first generated.
resultType | CRRenderResultType. Specifies whether the page will be rendered using strings or arrays. See Remarks below.

Returns

Returns the HTML stream.

Remarks

Currently only arrays are supported.


Pages Collection

The Pages Collection is part of the Page Engine. Use the Page Engine when designing web sites using Active Server Pages, the Crystal Report Engine Automation Server, and the Crystal Design-Time ActiveX Control. Unless you are experienced with the Crystal Report Engine Object Library, you should allow the Crystal Design-Time ActiveX Control to generate VBScript code in your Active Server Pages that controls the Page Engine objects.

The Page Engine generates pages of a report on the web server and sends the pages to client web browsers as they are requested. For example, when a user first requests a report, only the first page is sent to the web browser. If the user pages forward or backward in the report, or requests a specific page, only that page is sent. This limits the resources required by the web server and reduces download time for the client browser.

The Pages Collection is a collection of Page Object. Access a specific Page Object in the collection using the Item property.

Pages Collection Properties

Property | Description | Read/Write | Restriction in event handler
Count | Long. Gets the number of page objects in the collection. | Read only | None
Item (index As Long) | Page Object. Gets the collection item based on the 1-based index number. | Read only | None
Parent | PageGenerator Object. Gets reference to the parent object. | Read only | None

Remarks

Item is a default property. You can reference a page directly, for example, Pages(1).


ParameterFieldDefinition Object

The ParameterFieldDefinition Object represents a parameter field in the report. This object provides properties and methods for retrieving information and setting options for a parameter field in your report (that is, current value, default value, etc.). A ParameterFieldDefinition Object is obtain from the Field property of the FieldObject Object, when the specified field is a parameter field or from the ParameterFieldDefinitions Collection Object under Report.

ParameterFieldDefinition Object Properties

Property | Description | Read/ Write | Restriction in event handler
DisallowEditing | Boolean. Gets or sets the disallowing editing option. | Read/Write | Can be written only when formatting idle.
DiscreteOrRange Kind | CRDiscreteOrRangeKind. Gets or sets the parameter value kind (discrete and/or range). | Read/Write | Can be written only when formatting idle.
EditMask | String. Gets or sets edit mask for string parameter. See Remarks below for additional information. | Read/Write | Can be written only when formatting idle.
EnableExclusive Group | Boolean. Works in conjunction with property PlaceInGroup. If EnableExclusiveGroup is TRUE, a Bool parameter group can have only one value set to TRUE; if FALSE, then the group can have multiple values set to TRUE. | Read/Write | Can be written only when formatting idle.
EnableMultiple Values | Boolean. Gets or sets the allow multiple values option. | Read/Write | Can be written only when formatting idle.
EnableNullValue | Boolean. Gets or sets the value nullable option for Stored Procedure parameters. | Read/Write | Can be written only when formatting idle.
EnableRangeLimit | Boolean. Gets or sets the option which specifies if this parameter field value should be in the specified range. | Read/Write | Can be written only when formatting idle.
EnableShow DescriptionOnly | Boolean. Gets or sets the show description for pick list option. | Read/Write | Can be written only when formatting idle.
EnableSortBasedOn Desc | Boolean. Gets or sets the sort based on description in pick list option. | Read/Write | Can be written only when formatting idle.
GroupNumber | Integer. Gets or sets boolean group number. | Read/Write | Can be written only when formatting idle.
IsCurrentValueSet | Boolean. Gets whether the current value has been set. | Read only | None
IsDefaultValueSet | Boolean. Gets whether the default value has been set. | Read only | None
Kind | CRFieldKind. Gets which kind of field (database, summary, formula, etc.). | Read only | None
MaximumValue | Variant. Gets or sets the maximum value. See Remarks below for additional comments. | Read/Write | Can be written only when formatting idle.
MinimumValue | Variant. Gets or sets minimum value. See Remarks below for additional comments. | Read/Write | Can be written only when formatting idle.
Name | String. Gets the unique formula name of the parameter field as it appears in the Parameter Field list (RDC DataView). | Read only | None
NeedsCurrentValue | Boolean. Gets whether the field needs a current value. | Read only | None
NextValue | Variant. Gets the next field value. | Read only | Can be read only when top-level Report object is formatting active.
NthValue Description (index As Integer) | String. Gets or sets nth value description. | Read/Write | Can be written only when formatting idle.
NumberOfBytes | Integer. Gets the number of bytes required to store the field data in memory. | Read only | None
NumberOfCurrent Ranges | Integer. Gets total number of current ranges. | Read only | None
NumberOfCurrent Values | Integer. Gets the total number of current values. | Read only | None
NumberOfDefault Values | Integer. Gets the total number of default values. | Read only | None
ParameterField Name | String. Gets the name of the parameter field as it is displayed (referenced) in the report (RDC DataView). | Read only | None
ParameterType | CRParameterFieldType. Gets parameter type. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None
PickListSortMethod | CRParameterPickListSortMethod. Gets or sets the sort method in pick list option. | Read/Write | Can be written only when formatting idle.
PlaceInGroup | Boolean. Gets or sets, when prompting for values, whether a Boolean parameter field should appear as part of a Boolean parameter group or individually. Used in conjunction with Boolean property EnableExclusiveGroup. | Read/Write | Can be written only when formatting idle.
PreviousValue | Variant. Gets the field previous value. | Read only | Can be read only when top-level Report object is formattiong active.
Prompt | String. Gets or sets the parameter field prompting string. | Read/Write | None
ReportName | String. Gets the report name the parameter field is in. If it is a main report, the ReportName is empty. | Read only | None
Value | Variant. Gets the current value of the field. | Read only | Can be read only when top-level Report object is formatting active.
ValueType | CRFieldValueType. Gets which type of value is found in the field. | Read only | None

Remarks
  • Regarding property EditMask, please see the additional information available in Crystal Reports Online Help. Search for "Edit Parameter Field dialog box" in the SCR Online Help index.
  • Regarding properties MaximumValue and MinimumValue, the following comments apply.
      • All parameter field types: EnableRangeLimit property must be set to TRUE for MaximumValue and Minimum Value properties to have an effect.
      • String parameter fields: The properties provide the maximum and minimum lengths of the string, not a value range.
      • Boolean parameter fields: The properties do not apply.
  • Regarding properties EditMask, MaximumValue and MinimumValue, changing values associated with one or more of these properties may result in the loss of default values that do not fall within the scope of the new EditMask, MaximumValue or MinimumValue properties.


ParameterFieldDefinition Object Methods

The following methods are discussed in this section:

AddCurrentRange Method (ParameterFieldDefinition Object)

AddCurrentValue Method (ParameterFieldDefinition Object)

AddDefaultValue Method (ParameterFieldDefinition Object)

ClearCurrentValueAndRange Method (ParameterFieldDefinition Object)

DeleteNthDefaultValue Method (ParameterFieldDefinition Object)

GetNthCurrentRange Method (ParameterFieldDefinition Object)

GetNthCurrentValue Method (ParameterFieldDefinition Object)

GetNthDefaultValue Method (ParameterFieldDefinition Object)

SetNthDefaultValue Method (ParameterFieldDefinition Object)


AddCurrentRange Method (ParameterFieldDefinition Object)

The AddCurrentRange method adds the current parameter range to the specified parameter field of a report. When this method is used, property DiscreteOrRangeKind must be crRangeValue.

Syntax

Sub AddCurrentRange (start, end, rangeInfo As CRRangeInfo)

Parameters

Parameter | Description
start | Sets start of the value range.
end | Sets end of the value range.
rangeInfo | CRRangeInfo. Use this bitwise value to indicate whether the upper and/or lower bound of the range should be included.


AddCurrentValue Method (ParameterFieldDefinition Object)

The AddCurrentValue method adds a value to the specified parameter field of a report. When this method is used, property DiscreteOrRangeKind must be crDiscreteValue.

Syntax

Sub AddCurrentValue (CurrentValue)

Parameter

Parameter | Description
CurrentValue | Specifies the current value to be added.


AddDefaultValue Method (ParameterFieldDefinition Object)

The AddDefaultValue method adds a value to the group of default values for a specified parameter in a report. The default value set should fall within the scope of properties EditMask and MaximumValue and MinimumValue, if set. Use this method instead of SetDefaultValue if the parameter field allows multiple values.

Syntax

Sub AddDefaultValue (DefaultValue)

Parameter

Parameter | Description
DefaultValue | Specifies the default value to be added.


ClearCurrentValueAndRange Method
(ParameterFieldDefinition Object)

The ClearCurrentValueAndRange method clears the specified parameter field of all current values and ranges.

Syntax

Sub ClearCurrentValueAndRange ()


DeleteNthDefaultValue Method (ParameterFieldDefinition Object)

The DeleteNthDefaultValue method deletes the nth default value of the parameter field.

Syntax

Sub DeleteNthDefaultValue(index As Integer)

Parameter

Parameter | Description
index | Index of the value to be deleted.


GetNthCurrentRange Method (ParameterFieldDefinition Object)

The GetNthCurrentRange method retrieves a value range from the specified parameter field in a report.

Syntax
Sub GetNthCurrentRange (index As Integer, pStart, pEnd,

    pRangeInfo As CRRangeInfo)
Parameters

Parameter | Description
index | Index of the value range to be retrieved.
pStart | Sets start of the value range.
pEnd | Sets end of the value range.
pRangeInfo | CRRangeInfo. Use this bitwise value to indicate whether the upper and/or lower bound of the range should be included.


GetNthCurrentValue Method (ParameterFieldDefinition Object)

The GetNthCurrentValue method returns a value from the specified parameter field of a report.

Syntax

Function GetNthCurrentValue (index As Integer)

Parameter

Parameter | Description
index | Index number of the current value to be retrieved.

Returns

Returns the current value specified by the index parameter.


GetNthDefaultValue Method (ParameterFieldDefinition Object)

Get NthDefaultValue method retrieves a default value for a specified parameter field in a report.

Syntax

Function GetNthDefaultValue (index As Integer)

Parameter

Parameter | Description
index | The index number of the default value to be retrieved.

Returns

Returns the default value specified by the index parameter.


SetNthDefaultValue Method (ParameterFieldDefinition Object)

The SetNthDefaultValue method sets a default value for a specified parameter field in a report. The default value set should fall within range and property EditMask if a string field, if set.

Syntax

Sub SetNthDefaultValue (index As Integer, nthDefaultValue)

Parameters

Parameter | Description
index | The index number of the default value to be set.
nthDefaultValue | Specifies the default value that you want to set for parameter field.


ParameterFieldDefinitions Collection

The ParameterFieldDefinitions Collection is a collection of parameter fields in the report. If the report contains any subreports, parameter fields in the subreports will also be included in the collection. Access a specific ParameterFieldDefinition.

ParameterFieldDefinitions Collection Properties

Property | Description | Read/ Write | Restriction in event handler
Count | Long. Gets the number of parameter fields in the collection. | Read only | None
Item (index As Long) | ParameterFieldDefinition Object. Gets the item in the Collection specified by parameter index. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None

Remarks

Item is a default property. You can reference a parameter field directly, for example, ParameterFieldDefinitions(1).


ParameterFieldDefinitions Collection Methods

The following methods are discussed in this section:

Add Method (ParameterFieldDefinitions Collection)

Delete Method (ParameterFieldDefinitions Collection)


Add Method (ParameterFieldDefinitions Collection)

Use Add method to add a ParameterFieldDefinition Object, to the ParameterFieldDefinitions Collection.

Syntax
Function Add (parameterName As String, ValueType As CRFieldValueType

    ) As ParameterFieldDefinition
Parameters

Parameter | Description
parameterName | Specifies the parameter name.
ValueType | CRFieldValueType. Specifies the value type of the field.

Returns

Returns the ParameterFieldDefinition Object added to the Collection


Delete Method (ParameterFieldDefinitions Collection)

Use Delete method to remove a ParameterFieldDefinition Object from the Collection.

Syntax

Sub Delete (index)

Parameter

Parameter | Description
index | Specifies the index number of the item that you want to delete from the Collection.


PrintingStatus Object

The PrintingStatus Object provides properties for retrieving information and setting options for the printing status of a report (for example, number of pages, latest page to be printed, etc.). A PrintingStatus Object is obtained from the PrintingStatus property of the Report Object.

PrintingStatus Object Properties

Property | Description | Read/Write | Restriction in event handler
NumberOfPages | Long. Gets the total number of pages in the report. | Read only | None
NumberOfRecord Printed | Long. Gets the number of records printed. | Read only | None
NumberOfRecordRead | Long. Gets the number of records read. | Read only | None
NumberOfRecord Selected | Long. Gets the number of records selected. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None
Progress | CRPrintingProgress. Gets the printing progress. | Read only | None


Report Object

A report corresponds to a print job in the Crystal Report Engine. When the report object is destroyed, or goes out of focus, it closes the print job. It holds on to Application Object. When a Report Object gets destroyed, it releases the application.

Access to the Report Object is dependent on the object variable you create. If the object variable goes out of scope, you will lose access to the Report Object and, therefore, the report. You may want to declare your Report Object variable as Global.

Report Object Properties

Property | Description | Read/ Write | Restriction in event handler
Application | Application Object. Gets reference to the Application Object that the Report Object is associated with. | Read only | None
Application Name | String. Gets or sets the application name. | Read/Write | None
Areas | Areas Collection. Gets reference to the Areas Collection, a collection of all the areas in the report which can be indexed by a number or by a string, such as "RH", "GF1". The areas are in the same order as on the Crystal Reports Design Tab. For Example: RH, PH, GH1,...GHn, D, GFn,...GF1, RF, PF. The abbreviations for areas are case sensitive. | Read only | None
BottomMargin | Long. Gets or sets the page bottom margin, in twips. | Read/Write | Can be written only when formatting idle.
CanPerform GroupingOn Server | Boolean. Gets whether the report can perform grouping on the server. | Read only | None
CaseInsensitive SQLData | Boolean. Gets or sets the report option that indicates whether the SQL data used in the report becomes case sensitive. | Read/Write | Can be written only when formatting idle.
ConvertDate TimeType | CRConvertDateTimeType. Gets or sets the report option that specifies the format to be converted for date/time fields. | Read/Write | Can be written only when formatting idle.
ConvertNull FieldToDefault | Boolean. Gets or sets the report option that indicates whether to convert any null values to the database field default. | Read/Write | Can be written only when formatting idle.
Database | Database Object. Gets reference to the Database Object which represents the database used in the report. | Read only | None
DisplayProgress Dialog | Boolean. Enable or disable the progress dialog. | Read/Write | Can be written only when formatting idle.
DriverName | String. Gets the printer driver name used by the current report. Gets an empty string if default printer is used. | Read only | Can be written only when formatting idle.
EnableAsync Query | Boolean. Gets or sets the enable AsyncQuery | Read/Write | Can be written only when formatting idle.
EnableGenerating DataForHidden Object | Boolean. Gets or sets the Enable Generating Data For Hidden Object option. | Read/Write | Can be written only when formatting idle.
EnableParameter Prompting | Boolean. Gets or sets the prompting for parameter fields option. | Read/Write | Can be written only when formatting idle.
EnablePerform Queries Asynchronously | Boolean. Gets or sets the perform queries asynchronously option | Read/Write | Can be written only when formatting idle.
EnableSelect DistinctRecords | Boolean. Gets or sets the select distinct records option | Read/Write | Can be written only when formatting idle.
ExportOptions | ExportOptions Object. Gets reference to ExportOptions Object for the report. | Read only | None
FieldMapping Type | CRFieldMappingType. Gets or sets the field mapping type. | Read/Write | Can be written only when formatting idle.
FormulaFields | FormulaFieldDefinitions Collection. Gets reference to Collection of all the named FormulaFieldDefinitions defined in the Report. | Read only | None
FormulaSyntax | CRFormulaSyntax. Gets or sets report formula syntax. | Read/Write | Can be written only when formatting idle.
GroupName Fields | GroupNameFieldDefinitions Collection. Gets reference to a collection of all the group name fields defined in the report. | Read only | None
GroupSelection Formula | String. Gets or sets the group selection formula. | Read/Write | Can be written only when formatting idle.
GroupSortFields | SortFields Collection. Gets reference to group sort field collection. | Read only | None
HasSavedData | Boolean. Gets whether the report has data saved in memory. | Read only | None
KeywordsIn Report | String. Gets or sets the keywords in the report. | Read/Write | Can be written only when formatting idle.
Kind | CRReportKind. Gets what kind of report. | Read only | None
LastGetFormula Syntax | CRFormulaSyntax. Gets the formula syntax of the last formula text returned. | Read only | None
LeftMargin | Long. Gets or sets the page left margin, in twips. | Read/Write | Can be written only when formatting idle.
MorePrintEngine ErrorMessages | Boolean. Gets or sets the report option that indicates whether to pop up database error dialogs during printing when a Report Engine error occurs. | Read/Write | Can be written only when formatting idle.
NumberOfGroup | Long. Gets the number of groups in the report. | Read only | None
PageEngine | PageEngine Object. Gets reference to the PageEngine object. | Read only | None
PaperOrientation | CRPaperOrientation. Gets or sets the current printer paper orientation. For the default printer, crDefaultPaperOrientation is returned. | Read/Write | Can be written only when formatting idle.
PaperSize | CRPaperSize. Gets or sets the current printer paper size. For the default printer, crDefaultPaperSize is returned. | Read/Write | Can be read or written only when formatting idle.
PaperSource | CRPaperSource. Gets or sets the current printer paper source. | Read/Write | Can be written only when formatting idle.
ParameterFields | ParameterFieldDefinitions Collection. Gets reference to the collection of all the ParameterFieldDefinitions defined in the report. This property will return parameter fields found in the main report as well as any subreports included in the report (for example, if the main report has 3 parameters and a subreport included within the report has an additional 2 parameters, the number of parameter fields in the collection returned by Report.ParameterFields would be 5). | Read only | None
Parent | Report Object. Gets reference to the parent object for subreports. (NULL for main report). | Read only | None
PerformGrouping OnServer | Boolean. Gets or sets the performing grouping on server option. | Read/Write | Can be written only when formatting idle.
PortName | String. Gets the printer port name used by the current report. Gets an empty string if the default printer is used. | Read only | None
PrintDate | Date. Gets or sets the print date for the report. By default, the current date will be used. | Read/Write | Can be written only when formatting idle.
PrinterDuplex | CRPrinterDuplexType. Gets or sets the current printer duplex option. | Read/Write | Can be written only when formatting idle.
PrinterName | String. Gets the printer name used by the report. Gets an empty string if the default printer is used. | Read only | None
PrintingStatus | PrintingStatus Object. Gets PrintingStatus Object for the report. | Read only | None
RecordSelection Formula | String. Gets or sets record selection formula. | Read/Write | Can be written only when formatting idle.
RecordSortFields | SortFields Collection. Gets a collection of record sort fields. | Read only | None
ReportAlerts | ReportAlerts Collection. Gets reference to Collection of all the named Report Alerts defined in the Report. | Read only | None
ReportAuthor | String. Gets or sets the report author. | Read/Write | Can be written only when formatting idle.
ReportComments | String. Gets or sets report comments. | Read/Write | Can be written only when formatting idle.
ReportSubject | String. Gets or sets the report subject. | Read/Write | Can be written only when formatting idle.
ReportTemplate | String. Gets or sets the report template. | Read/Write | Can be written only when formatting idle.
ReportTitle | String. Gets or sets the report title. | Read/Write | Can be written only when formatting idle.
RightMargin | Long. Gets or sets the page right margin, in twips. | Read/Write | Can be written only when formatting idle.
RunningTotal Fields | RunningTotalFieldDefinitions Collection. Gets running total fields collection. | Read only | None
SavePreview Picture | Boolean. Gets or sets save preview picture with report option. | Read/Write | None
Sections | Sections Collection. Gets collection of all the sections in the report. | Read only | None
SQLExpression Fields | SQLExpressionFieldDefinitions Collection. Gets SQL expression field collection. | Read only | None
SQLQueryString | String. Gets or sets SQL query string. | Read/Write | Can be written only when formatting idle.
SummaryFields | SummaryFieldDefinitions Collection. Gets collection for group and report summaries (cross-tab summaries not available using this property). | Read only | None
TopMargin | Long. Gets or sets the page top margin, in twips. | Read/Write | Can be written only when formatting idle.
TranslateDos Memos | Boolean. Gets or sets the report option that indicates whether to translate DOS memos. | Read/Write | Can be written only when formatting idle.
TranslateDos Strings | Boolean. Gets or sets the report option that indicates whether to translate DOS strings. | Read/Write | Can be written only when formatting idle.
UseIndexFor Speed | Boolean. Gets or sets the use index for speed during record selection report option. | Read/Write | Can be written only when formatting idle.
VerifyOnEvery Print | Boolean. Gets or sets the report option that indicates whether to verify the database every time the report is printed. | Read/Write | Can be written only when formatting idle.


Report Object Methods

The following methods are discussed in this section:

AddGroup Method (Report Object)—RDC Object Model

AddReportVariable Method (Report Object)

AutoSetUnboundFieldSource Method (Report Object)

CancelPrinting Method (Report Object)

DeleteGroup Method (Report Object)

DiscardSavedData Method (Report Object)

Export Method (Report Object)

GetNextRows Method (Report Object)

GetReportVariableValue Method (Report Object)

OpenSubreport Method (Report Object)

PrinterSetup Method (Report Object)

PrintOut Method (Report Object)

ReadRecords Method (Report Object)

SaveAs Method (Report Object)

SelectPrinter Method (Report Object)

SetDialogParentWindow Method (Report Object)

SetReportVariableValue Method (Report Object)

SetUnboundFieldSource Method (FieldObject Object)


AddGroup Method (Report Object)—RDC Object Model

The AddGroup Method adds a group to the report. ConditionField indicates the field for grouping, Condition indicates a change in a field value that generates a grouping, and SortDirection specifies the direction in which groups are sorted.

Syntax
Sub AddGroup (GroupNumber As Integer, pConditionField As Object,

    Condition As CRGroupCondition, SortDirection As CRSortDirection)
Parameters

Parameter | Description
GroupNumber | Specifies the number of the group to be added (the position of the group in relation to existing groups). For example, to add a group to the first position, set GroupNumber=1.
pConditionField | Specifies the field to be grouped. The field can be a database field definition object or the field name
condition | CRGroupCondition. Specifies CRGroupCondition (see table below) indicating the grouping condition (that is, group on any value).
SortDirection | CRSortDirection. Specifies the sort direction for the group.


AddReportVariable Method (Report Object)

Use AddReportVariable method to add a report variable to the report. This variable can then be used to provide a calculated field value in the Format Event. You can add as many report variables to your report as you need. Each report variable is identified by its name, which must be unique.

Syntax
Sub AddReportVariable (type As CRReportVariableValueType,

    pName As String, [arraySize As Long], [reserved])
Parameters

Parameter | Description
type | CRReportVariableValueType. Specifies the type of variable that you want to add to the report.
pName | Specifies the unique name for the report variable that you want to add.
[arraySize As Long] | Reserved. Do not use.
[reserved] | Reserved. Do not use.


AutoSetUnboundFieldSource Method (Report Object)

Use AutoSetUnboundFieldSource method to automatically bind unbound report fields to database fields based on the unbound field's name or name and value type.

Syntax
Sub AutoSetUnboundFieldSource (matchType As CRBindingMatchType,

    [bindSubReports])
Parameters

Parameter | Description
matchType | CRBindingMatchType. Specifies whether to match name alone or name and data type.
[bindSubReports] | Specifies whether or not to bind subreport unbound fields.


CancelPrinting Method (Report Object)

Use CancelPrinting method to cancel the printing of a report.

Syntax

Sub CancelPrinting ()


DeleteGroup Method (Report Object)

Use DeleteGroup method to remove a group from a report.

Syntax

Sub DeleteGroup (GroupNumber As Integer)

Parameter

Parameter | Description
GroupNumber | Specifies the index number of the group that you want to delete from the report.


DiscardSavedData Method (Report Object)

Use DiscardSavedData method to discard any saved data with the report before previewing. This method can be invoked only when in formatting idle mode.

Syntax

Sub DiscardSavedData ()


Export Method (Report Object)

Use Export method to export reports to a format and destination specified with ExportOptions Object.

Syntax

Sub Export ([promptUser])

Parameters

Parameter | Description
[promptUser] | Specifies Boolean value indicating if user should be prompted for export options. If you don't want to prompt the user, then you must set all necessary export options. The application will prompt automatically for any missing export options, even if promptUser = FALSE. Default value = TRUE (prompt user).


GetNextRows Method (Report Object)

Use GetNextRows method to get the specified rowset.

Syntax

Function GetNextRows (startRowN As Long, pRowN As Long)

Parameters

Parameter | Description
startRowN | Specifies the row number to start the rowset on.
pRowN | Specifies the number of rows to return to the rowset.

Returns

Returns the specified rowset.


GetReportVariableValue Method (Report Object)

Use GetReportVariableValue method to get the value of the specified uniquely named report variable. This call can only be made in the formatting active mode.

Syntax

Function GetReportVariableValue (pName As String)

Parameters

Parameter | Description
pName | Specifies the unique name of the report variable for which you want to get the value.

Returns

Returns value of the specified report variable.


OpenSubreport Method (Report Object)

The OpenSubreport method opens a subreport contained in the report and returns a Report Object corresponding to the named subreport.

Syntax

Function OpenSubreport (pSubreportName As String) As Report

Parameter

Parameter | Description
pSubreportName | Specifies the file name of the subreport to be opened.

Returns

Returns the specified subreport as a Report Object.


PrinterSetup Method (Report Object)

Use PrinterSetup method to open the printer setup dialog box so that the user can change printers or printer settings for the report.

Syntax
Sub PrinterSetup (hWnd As Long)
Parameter

Parameter | Description
hWnd | Specifies the handle of the printer setup dialog box parent window. If you pass 0, the top level application window will be the parent.


PrintOut Method (Report Object)

Use PrintOut method to print out the specified pages of the report to the printer selected using the SelectPrinter Method (Report Object). If no printer is selected, the default printer specified in the report will be used. This method can be invoked only when in formatting idle mode.

Syntax
Sub PrintOut ([promptUser], [numberOfCopy], [collated],

    [startPageN], [stopPageN])
Parameters

Parameter | Description
[promptUser] | Specifies Boolean value indicating if the user should be prompted for printer options.
[numberOfCopy] | Specifies the number of report copies you want printed.
[collated] | Specifies Boolean value specifying whether or not you want the report copies collated.
[startPageN] | Specifies the first page that you want printed.
[stopPageN] | Specifies the last page that you want printed.


ReadRecords Method (Report Object)

Use ReadRecords method to force the report to read all records in the report from the database.

Syntax

Sub ReadRecords ()


SaveAs Method (Report Object)

Use SaveAs method to save a report with the ability to specify Crystal Reports 8 or 7 version file format. The user can specify which format to use when saving the report. This call can only be made in formatting idle mode.

Syntax

Sub SaveAs (pFilePath As String, fileFormat As CRReportFileFormat)

Parameters

Parameter | Description
pFilePath | Specifies the file path and name that you want to use to save the report.
fileFormat | CRReportFileFormat. Specifies the file format that you want to use to save the report.


SelectPrinter Method (Report Object)

The SelectPrinter method selects a different printer for the report. This method can be invoked only when in formatting idle mode.

Syntax
Sub SelectPrinter (pDriverName As String, pPrinterName As String,
pPortName As String)
Parameters

Parameter | Description
pDriverName | Specifies the name of the printer driver for the selected printer.
pPrinterName | Specifies the printer name for the selected printer.
pPortName | Specifies the port name for the port to which the selected printer is attached.


SetDialogParentWindow Method (Report Object)

The SetDialogParentWindow method sets the dialog parent window.

Syntax

Sub SetDialogParentWindow (hWnd As Long)

Parameter

Parameter | Description
hWnd | Specifies the handle of the parent window.


SetReportVariableValue Method (Report Object)

Use SetReportVariableValue method to set the value of a report variable into the Print Engine. The report variable is designed to be used in Format Event to do calculated fields. However, you should not depend on how many times an event is fired to do total calculations -- make sure that the calculation for the report variable is correct. The Print Engine keeps track of the status. This call can me made only in formatting active mode.

Syntax

Sub SetReportVariableValue (pName As String, var)

Parameters

Property | Description
pName | Specifies the name of the variable for which you want to set the value.
var | Specifies the value that you want to set.


Report Object Events

The following events are discussed in this section:

AfterFormatPage Event (Report Object)

BeforeFormatPage Event (Report Object)

FieldMapping Event (Report Object)

NoData Event (Report Object)


AfterFormatPage Event (Report Object)

The AfterFormatPage event is fired after formatting a page.

Syntax

Event AfterFormatPage (PageNumber As Long)

Parameter

Parameter | Description
PageNumber | Specifies the number of the report page triggering the event.


BeforeFormatPage Event (Report Object)

The BeforeFormatPage event is fired before formatting a page.

Syntax

Event BeforeFormatPage (PageNumber As Long)

Parameter

Parameter | Description
PageNumber | Specifies the number of the report page triggering the event.


FieldMapping Event (Report Object)

The FieldMapping event fires if the database is changed while verifying database.

Syntax
Event FieldMapping (reportFieldArray, databaseFieldArray,

    useDefault As Boolean)
Parameters

Parameter | Description
reportFieldArray | Specifies the report field array to map.
databaseFieldArray | Specifies the database field array to map.
useDefault | If TRUE, the values passed with parameters reportFieldArray and databaseFieldArray will be ignored and the default values used; if FALSE, the values passed with reportFieldArray and databaseFieldArray will be used.


NoData Event (Report Object)

The NoData event fires when there is no data for the report.

Syntax

Event NoData (pCancel As Boolean)

Parameter

Parameter | Description
pCancel | Specifies whether to cancel the report.


ReportAlert Object

The ReportAlert object represents a Report Alert contained in a report. This object provides properties for getting and setting information on Report Alerts in the report.

Report Alerts are custom messages created in either the Crystal Reports Designer, the Report Designer Component, or the Embeddable Crystal Reports Designer Control. Report Alerts may indicate action to be taken by the user or information about report data. ReportAlert Object Properties. For more information see Report Alerts in the Crystal Reports User's Guide.

ReportAlert Object Properties

Property | Definition | Read/ Write | Restriction in event handler
AlertInstances | ReportAlertInstances Collection. Gets a reference to a collection of all the Report Alert instances created when the Report Alert is run. | Read only | None
ConditionFormula | String. Gets or sets the condition formula for the Report Alert. The condition formula can be based on recurring records or on summary fields, but cannot be based on print-time fields, such as running totals or print time formulas. Condition formulas cannot have shared variables. | Read/Write | Can be written only when formatting idle.
DefaultMessage | String. Gets or sets the default message for the Report Alert. | Read/Write | Can be written only when formatting idle.
IsEnabled | Boolean. Gets or sets wether or not the Report Alert is enabled. | Read/Write | Can be written only when formatting idle
MessageFormula | String. Gets or sets the message when the Report Alert is triggered. The result of the formula must be a string, and is created by combining a string with a report field. If MessageFormula is set it will override the value set for DefaultMessage. | Read/Write | Can be written only when formatting idle
Name | String. Gets or sets the name of the Report Alert. | Read/Write | Can be written only when formatting idle
Parent | Report Object. Gets reference to the parent object. | Read only | None


ReportAlerts Collection

The ReportAlerts collection contains the Report Alert objects defined in a report. Access a specific ReportAlert Object, in the collection using the Item property.

ReportAlerts Collection Properties

Property | Definition | Read/ Write | Restriction in event handler
Count | Long. Gets the number of ReportAlert Object, in the collection. | Read only | None
Item (index As Long) | ReportAlert Object. Gets an item from the Collection. Item has an index parameter that is a 1-based index (for example, Item(1) for the first Report Alert in the collection). The items in the collection are indexed in the order that they were added to the report. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None

ReportAlerts Collection Methods

The following methods are discussed in this section:

Add Method (ReportAlerts Collection)

Delete Method (ReportAlerts Collection)


Add Method (ReportAlerts Collection)

The Add method is used to add a Report Alert object to the report.

Syntax

Function Add (Name As String, DefaultMessage As String, IsEnabled As Boolean, ConditionFormula As String, [MessageFormula as String]) As ReportAlert

Parameter | Description
Name | Specifies the name of the Report Alert.
DefaultMessage | Specifies the default message created by the Report Alert.
IsEnabled | Specifies wether or not the Report Alert is enabled when the report is run.
ConditionFormula | Specifies the conditional formula that evaluates when the Report Alert is triggered.
MessageFormula | Optional. Formula used to create the message when the Report Alert is triggered. The result of the formula must be a string, and is created by combining a string with a report field. If MessageFormula is set it will override the value set for DefaultMessage.

Sample

In this example a report is grouped by country and contains a summary of last year's sales per country. The Report Alert will be triggered when the summary of last year's sales exceeds $25,000.00. When the Report Alert is triggered a message is created from the default message and the country name.

Dim name, defaultMessage, conditionFormula, messageFormula As String

'Name of the Report Alert
name = "Sales Alert"

defaultMessage = "Great sales in "

'Conditional formula used to evaluate the Report Alert
conditionFormula = "Sum ({Customer.Last Year's Sales},
{Customer.Country}) > 25000"

'Replaces the default message set for the Report Alert. The message is
'created in a formula by concatenating the value set in the
'DefaultMessage parameter, and the group name of the country that
'triggers the Report Alert.
'DefaultAttribute is a function used by the Formula Editor to return
'the default message set for the Report Alert.
messageFormula = "DefaultAttribute & GroupName ({Customer.Country})"

Report.ReportAlerts.Add _
name, defaultMessage, True, conditionFormula, messageFormula


Delete Method (ReportAlerts Collection)

Use Delete method to remove a ReportAlert Object from the Collection.

Syntax

Sub Delete (index)

Parameter

Parameter | Description
index | Specifies the index number of the Object that you want to remove from the Collection.


ReportAlertInstance Object

A ReportAlertInstance object is created each time a Report Alert is triggered. This object contains a property for getting the message created for that specific instance of the Report Alert.

Note: In the present build only the first ReportAlertInstance is created at runtime. This limitation will be addressed in a future release.

ReportAlertInstance Object Properties

PropertLy | Definition | Read/Write | Restriction in event handler
AlertMessage | String. Gets the message returned at the time the Report Alert was triggered. | Read only | None
Parent | ReportAlert Object. Gets reference to the parent object. | Read only | None


ReportAlertInstances Collection

The ReportAlertInstances collection contains the ReportAlertInstance objects created when a Report Alert is triggered. Access a specific ReportAlertInstance Object, in the collection using the Item property.

Note: In the present build only the first ReportAlertInstance is created at runtime. This limitation will be addressed in a future release.

ReportAlertInstances Properties

Property Definition Read/ Write Restriction in
event handler

Count

Long. Gets the number of ReportAlertInstance Object, in the collection.

Read only

None

Item (index
As Long)

ReportAlertInstance Object. Gets an item from the Collection. Item has an index parameter that is a 1-based index (for example, Item(1) for the first ReportAlertInstance in the collection). The items in the collection are indexed in the order that they were added to the report.

Note: In the present build only the first ReportAlertInstance is created at runtime. This limitation will be addressed in a future release.

Read only

None

Parent

ReportAlert Object. Gets reference to the parent object.

Read only

None


ReportObjects Collection

The ReportObjects Collection is a collection of report objects in a section. Report objects can be a field, text, OLE, cross-tab, subreport, BLOB field, Box, Graph, Line, Map, or OlapGrid objects. Access a specific object in the collection using the Item property.

ReportObjects Collection Properties

Property | Description | Read/ Write | Restriction in event handler
Count | Long. Gets the number of report objects in the collection. | Read only | None
Item (index) As Object | Gets a report object. Depending on the type of item referenced, this can be a BlobFieldObject Object, FieldObject Object, TextObject Object,Page Object, CrossTabObject Object, SubreportLinks Collection, , GraphObject Object, LineObject Object, MapObject Object, OlapGridObject Object. Item has an index parameter that is a numeric, 1-based index (that is, Item (1)). The items in the collection are indexed in the order they were added to the report. | Read only | None
Parent | Section Object. Gets reference to the parent object. | Read only | None

Remarks

Item is a default property. You can reference a report object directly, for example, ReportObjects(1).


RunningTotalFieldDefinition Object

The RunningTotalFieldDefinition Object represents a running total field used in the report. This object provides properties for getting information on running total fields in the report.

RunningTotalFieldDefinition Object Properties

Property | Definition | Read/ Write | Restriction in event handler
Evaluate Condition | CRRunningTotalCondition. Gets evaluate condition. | Read only | None
Evaluate ConditionField | Object. Gets evaluate condition field. | Read only | None
Evaluate ConditionFormula | String. Gets or sets evaluate condition formula. | Read/Write | Can be written only when formatting idle.
Evaluate GroupNumber | Integer. Gets or sets evaluate group number. | Read/Write | Can be written only when formatting idle.
Hierarchical SummaryType | CRHierarchicalSummaryType. Gets or sets wether or not to calculate the running total across the hierarchy in a hierarchically grouped report. | Read/Write | Can be written only when formatting idle.
Kind | CRFieldKind. Gets which kind of field (that is, database, summary, formula, etc.). | Read only | None
Name | String. Gets the unique formula name of the field within the report (table.FIELD). For example, {#Test}. | Read only | None
NextValue | Variant. Gets the field next value. | Read only | Can be read only when top-level Report object is formatting active.
NumberOfBytes | Integer. Gets the number of bytes required to store the field data in memory. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None
PreviousValue | Variant. Gets the field previous value. | Read only | Can be read only when top-level Report object is formatting active.
ResetCondition | CRRunningTotalCondition. Gets the reset condition. | Read only | None
ResetCondition Field | Object. Gets reset condition field. | Read only | None
Reset ConditionFormula | String. Gets or sets the reset condition formula. | Read/Write | Can be written only when formatting idle.
ResetGroupNumber | Integer. Gets or sets the reset group number. | Read/Write | Can be written only when formatting idle.
RunningTotal FieldName | String. Gets the running total field name. | Read only | None
Secondary SummarizedField | Object. Gets the secondary summarized field | Read only | Can be written only when formatting idle.
SummarizedField | Object. Gets the summarized field. | Read only | Can be written only when formatting idle.
Summary OperationParameter | Long. Gets or sets summary operation parameter. | Read/Write | Can be written only when formatting idle.
SummaryType | CRSummaryType. Gets or sets summary type. | Read/Write | Can be written only when formatting idle.
Value | Variant. Gets the field current value. | Read only | Can be read only when top-level Report object is formatting active.
ValueType | CRFieldValueType. Gets which type of value is found in the field. | Read only | None


RunningTotalFieldDefinition Object Methods

The following methods are discussed in this section:

SetEvaluateConditionField Method (RunningTotalFieldDefinition Object)

SetNoEvaluateCondition Method (RunningTotalFieldDefinition Object)

SetNoResetCondition Method (RunningTotalFieldDefinition Object)

SetResetConditionField Method (RunningTotalFieldDefinition Object)

SetSecondarySummarizedField Method (RunningTotalFieldDefinition Object)

SetSummarizedField Method (RunningTotalFieldDefinition Object)


SetEvaluateConditionField Method
(RunningTotalFieldDefinition Object)

Use SetEvaluateConditionField to set the evaluate condition field.

Syntax

Sub SetEvaluateConditionField (pEvaluateConditionField)

Parameter

Parameter | Description
pEvaluateConditionField | Specifies the condition field that you want to use.


SetNoEvaluateCondition Method (RunningTotalFieldDefinition Object)

Use SetNoEvaluateCondition method to specify no evaluate condition for the RunningTotalFieldDefinition Object.

Syntax

Sub SetNoEvaluateCondition ()


SetNoResetCondition Method (RunningTotalFieldDefinition Object)

Use SetNoResetCondition method to specify no reset condition for the RunningTotalFieldDefinition Object.

Syntax

Sub SetNoResetCondition ()


SetResetConditionField Method (RunningTotalFieldDefinition Object)

Use SetResetConditionField to specify the reset condition field to use with the RunningTotalFieldDefinition Object.

Syntax

Sub SetResetConditionField (pResetConditionField)

Parameter

Parameter | Description
pResetConditionField | Specifies the condition field that you want to use.


SetSecondarySummarizedField Method
(RunningTotalFieldDefinition Object)

Use SetSecondarySummarizedField method to specify which condition field you want to use as the second summarized field for the RunningTotalFieldDefinition Object.

Syntax

Sub SetSecondarySummarizedField (secondarySummariedField)

Parameter

Parameter | Description
secondarySummariedField | Specifies the condition field that you want to use.


SetSummarizedField Method (RunningTotalFieldDefinition Object)

Use SetSummarizedField method to specify a second summarized field for the RunningTotalFieldDefinition Object.

Syntax

Sub SetSummarizedField (SummarizedField)

Parameter

Parameter | Description
SummarizedField | Specifies the condition field that you want to use.


RunningTotalFieldDefinitions Collection

The RunningTotalFieldDefinitions Collection is a collection of running total field definition objects. One object exists in the collection for every running total field accessed by the report. Access a specific RunningTotalFieldDefinition Object, in the collection using the Item property.

RunningTotalFieldDefinitions Collection Properties

Property | Description | Read/Write | Restriction in event handler
Count | Long. Gets the number of RunningTotalFieldDefinition Object, in the collection. | Read only | None
Item (index As Long) | RunningTotalFieldDefinition Object. Gets an item from the Collection. Item has an index parameter that is a 1-based index (for example, Item(1) for the first database field in the collection). The items in the collection are indexed in the order that they were added to the report. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None

Remarks

Instead of using the Item property as shown, you can reference a database directly, for example, RunningTotalFieldDefinitions(1).


RunningTotalFieldDefinitions Collection Methods

The following methods are discussed in this section:

Add Method (RunningTotalFieldDefinitions Collection)

Delete Method (RunningTotalFieldDefinitions Collection)


Add Method (RunningTotalFieldDefinitions Collection)

Use Add method to add a RunningTotalFieldDefinition Object to the Collection.

Syntax
Function Add (runningTotalName As String) As RunningTotalFieldDefinition
Parameter

Parameter | Description
runningTotalName | Specifies the name of the RunningTotal field that you want to add.

Returns

Returns a RunningTotalFieldDefinition Object member of the Collection.


Delete Method (RunningTotalFieldDefinitions Collection)

Use Delete method to remove a RunningTotalFieldDefinition Object from the Collection.

Syntax

Sub Delete (index)

Parameter

Parameter | Description
index | Specifies the index number of the Object that you want to remove from the Collection.


Section Object

Report areas contain at least one section. The Section Object includes properties for accessing information regarding a section of your report. This object holds on to a report object, then releases the report object when it is destroyed.

Section Object Properties

Property | Description | Read/ Write | Restriction in event handler
BackColor | OLE_COLOR. Gets or sets the section background color. | Read/Write | Can be written only when formatting idle or active.
Height | Long. Gets or sets the height of the section, in twips. | Read/Write | Can be written only when formatting idle or active.
KeepTogether | Boolean. Gets or sets the option that indicates whether to keep the entire section on the same page if it is split into two pages. | Read/Write | Can be written only when formatting idle or active.
MinimumHeight | Long. Gets the minimum section height, in twips. | Read only | None
Name | String. Gets or sets the name of the section. | Read/Write | Can be written only when formatting idle.
NewPageAfter | Boolean. Gets or sets the option that indicates whether to start a new page after the current section. | Read/Write | Can be written only when formatting idle or active.
NewPageBefore | Boolean. Gets or sets the option that indicates whether to start a new page before the current section. | Read/Write | Can be written only when formatting idle or active.
Number | Integer. Gets the index number associated with the section in the area (for example, if the first section in an area, the number returned is 1). | Read only | None
Parent | Area Object. Gets reference to the parent object. | Read only | None
PrintAtBottomOf Page | Boolean. Gets or sets the option that indicates whether to print the current section at the bottom of the page. | Read/Write | Can be written only when formatting idle or active.
ReportObjects | ReportObjects Collection. Gets reference to the heterogeneous collection of report objects for the section. | Read only | None
ResetPage NumberAfter | Boolean. Gets or sets the option that indicates whether to reset the page number after the current section. | Read/Write | Can be written only when formatting idle or active.
Suppress | Boolean. Gets or sets the section visibility. | Read/Write | Can be written only when formatting idle or active.
SuppressIfBlank | Boolean. Gets or sets the option that indicates whether to suppress the current section if it is blank. | Read/Write | Can be written only when formatting idle or active.
UnderlaySection | Boolean. Gets or sets the underlay following section option. | Read/Write | Can be written only when formatting idle or active.
Width | Long. Gets the width of the section, in twips. | Read only | None


Section Object Methods

The following methods are discussed in this section:

AddBlobFieldObject Method (Section Object)

AddBoxObject Method (Section Object)

AddCrossTabObject Method (Section Object)

AddFieldObject Method (Section Object)

AddGraphObject Method (Section Object)

AddLineObject Method (Section Object)

AddPictureObject Method (Section Object)

AddSpecialVarFieldObject Method (Section Object)

AddSubreportObject Method (Section Object)

AddSummaryFieldObject Method (Section Object)

AddTextObject Method (Section Object)

AddUnboundFieldObject Method (Section Object)

DeleteObject Method (Section Object)

ImportSubreport Method (Section Object)


Section Object Events

Format Event (Section Object)


AddBlobFieldObject Method (Section Object)

The AddBlobFieldObject method adds a BlobFieldObject Object to the Section Object.

Syntax
Function AddBlobFieldObject (Field, Left As Long, Top As Long

    ) As BlobFieldObject
Parameters

Parameter | Description
Field | Variant. Can be formula form name or any field definition that specifies the field that you want to add.
Left | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Top | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.

Returns

Returns a BlobFieldObject Object.


AddBoxObject Method (Section Object)

The BoxObject method adds a to the Section Object.

Syntax
Function AddBoxObject (Left As Long, Top As Long, Right As Long,

    Bottom As Long, [pEndSection]) As BoxObject
Parameters

Parameter | Description
Left | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Top | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Right | Specifies the offset of the bottom right corner of the Object that you are adding relative to the bottom right corner of the parent (or end) Section, in twips.
Bottom | Specifies the offset of the bottom right corner of theObject that you are adding relative to the bottom right corner of the parent (or end) Section, in twips.
[pEndSection] | Specifies the Section in which the end of the BoxObject will be placed, if not the parent Section.

Returns

Returns a .


AddCrossTabObject Method (Section Object)

The AddCrossTabObject method adds a CrossTabObject Object to the Section Object. This method creates an empty CrossTabObject. Use the CrossTabObject properties and methods to add grouping and summary info.

Syntax
Function AddCrossTabObject (Left As Long, Top As Long) As CrossTabObject
Parameters

Parameter | Description
Left | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Top | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.

Returns

Returns a CrossTabObject Object.


AddFieldObject Method (Section Object)

The AddFieldObject method adds a FieldObject Object to the Section Object. The FieldObject can be reference to a database field definition, formula field definition, running total field definition, SQL expression field definition, or parameter field definition.

Syntax
Function AddFieldObject (Field, Left As Long, Top As Long) As FieldObject
Parameters

Parameter | Description
Field | Specifies the field that you want to add to the Section.
Left | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Top | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.

Returns

Returns a FieldObject Object.


AddGraphObject Method (Section Object)

The AddGraphObject method adds a GraphObject Object (Chart) to the Section Object. The inserted GraphObject is empty. Use the GraphObject properties and methods to add data, groups and settings. If optional parameter [pCrossTabObject] is passed, you can insert a CrossTab Chart.

Syntax
Function AddGraphObject (graphDataType As CRGraphDataType,

    Left As Long, Top As Long, [pCrossTabObject]) As GraphObject
Parameters

Parameter | Description
graphDataType | CRGraphDataType. Specifies the data type for the graph that you want to add.
Left | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Top | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
[pCrossTabObject] | If graphDataType=crCrossTabGraph, this parameter specifies the CrossTabObject to associate with the chart.

Returns

Returns a GraphObject Object.


AddLineObject Method (Section Object)

The AddLineObject method adds a LineObject Object to the Section Object. If optional parameter [pEndSection] is passed different from the current section, you can add a vertical line across sections.

Syntax
Function AddLineObject (Left As Long, Top As Long,

    Right As Long, Bottom As Long, [pEndSection]) As LineObject
Parameters

Parameter | Description
Left | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Top | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Right | Specifies the offset of the bottom right corner of theObject that you are adding relative to the bottom right corner of the parent (or end) Section, in twips.
Bottom | Specifies the offset of the bottom right corner of theObject that you are adding relative to the bottom right corner of the parent (or end) Section, in twips.
[pEndSection] | Specifies the Section in which the end of the LineObject will be placed, if not the parent Section.

Returns

Returns a LineObject Object.


AddPictureObject Method (Section Object)

The AddLineObject method adds a picture object from an image in the form of an OleObject Object to the Section Object.

Syntax
Function AddPictureObject (pImageFilePath As String, Left As Long,

    Top As Long) As OleObject
Parameters

Parameter | Description
pImageFilePath | Specifies the image file path and name that you want to add.
Left | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Top | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.

Returns

Returns a OleObject Object.


AddSpecialVarFieldObject Method (Section Object)

The SpecialVarFieldObject Method adds a SpecialVar FieldObject Object to the Section Object.

Syntax
Function AddSpecialVarFieldObject (specialVarType As CRSpecialVarType,

    Left As Long, Top As Long) As FieldObject
Parameters

Parameter | Description
specialVarType | CRSpecialVarType. Specifies the SpecialVar type.
Left | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Top | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.

Returns

Returns a FieldObject Object.


AddSubreportObject Method (Section Object)

The SubReportObject method adds a SubreportObject Object to the Section Object. This method adds an empty subreport to the Section. You can then add Objects and Sections to the SubreportObject.

Syntax
Function AddSubreportObject (pSubreportName As String,

    Left As Long, Top As Long) As SubreportObject
Parameters

Parameter | Description
pSubreportName | Specifies the name of the subreport that you want to add.
Left | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Top | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.

Returns

Returns a SubreportObject Object.


AddSummaryFieldObject Method (Section Object)

The AddSummaryField method adds a summary FieldObject Object to the Section Object.

Syntax
Function AddSummaryFieldObject (Field, SummaryType As CRSummaryType,

    Left As Long, Top As Long, [secondSummaryFieldOrFactor]) As
FieldObject
Parameters

Parameter | Description
Field | Specifies the summary field that you want to add.
SummaryType | CRSummaryType. Specifies the type of summary field.
Left | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Top | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
[secondSummary FieldOrFactor] | Specifies the second summary field or factor, if required by the summary type.

Returns

Returns a FieldObject Object.


AddTextObject Method (Section Object)

The AddTextObject method adds a TextObject Object to the Section Object. String parameter pText can contain formatting information such as tab stops and carriage returns.

Syntax

Function AddTextObject (pText As String,     Left As Long, Top As Long, [formatText]) As TextObject

Parameters

Parameter | Description
pText | Specifies the text that you want to add.
Left | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Top | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
[formatText] | Boolean. If TRUE, the text will be formatted according to the formatting characters included in the text string (for example, carriage returns, tabs, etc.). If FALSE, formatting characters in the text string will be ignored.

Returns

Returns a FieldObject Object.


AddUnboundFieldObject Method (Section Object)

The AddUnboundFieldObject method adds an unbound FieldObject Object to the Section Object. The unbound field can be bound to a Crystal Report formula or a data source at runtime.

Syntax
Function AddUnboundFieldObject (ValueType As CRFieldValueType,

    Left As Long, Top As Long) As FieldObject
Parameters

Parameter | Description
ValueType | CRFieldValueType. Specifies the type of value in the field.
Left | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Top | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.

Returns

Returns a FieldObject Object.


DeleteObject Method (Section Object)

The DeleteObject method removes an object from the Section Object

Syntax

Sub DeleteObject (reportObject)

Parameter

Parameter | Description
reportObject | Specifies the report object that you want to remove from the Section.


ImportSubreport Method (Section Object)

The ImportSubreport method imports a SubreportObject Object into the Section Object. With this call you can insert a subreport object obtained from an existing report file. The inserted Subreport Object will have all of the Objects and Sections of the original (source) report, except for Page Header and Page Footer Sections.

Syntax
Function ImportSubreport (subreportFileName As String,

    Left As Long, Top As Long) As SubreportObject
Parameters

Parameter | Description
subreportFileName | Specifies the name of the subreport that you want to import.
Left | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.
Top | Specifies the offset of the top left corner of the Object that you are adding relative to the top left corner of the parent Section, in twips.

Returns

Returns a SubreportObject Object.


Section Object Events

The following events are discussed in this section:

Format Event (Section Object)


Format Event (Section Object)

The Format event is fired before the print engine starts formatting a section. In the Format event handler you can use the object model to write some code to change the outcome of the formatted section. Be aware, however, that not all of the properties and methods provided in the object model are accessible at all times in the event handler. Specifically, only those properties and methods that have been marked "formatting active" or "no restrictions" can be used in the Event.

Syntax

Event Format (FormattingInfo As Object)

Parameter

Parameter | Description
FormattingInfo | The FormattingInfo object which will contain formatting information to be used by the Format event handler.

Remarks

The following comments regarding Restrictions and Rules apply to Format Event:

Restrictions

The Format event handler should not have any state. No matter when or how many times it is called it should always behave the same way. It should not keep track of how many times it is called and then, for example, change the background color based on how many times it has been called. The print engine formatting procedure is very complicated and one section can be formatted many times depending on different situations.

Note: Because the Format event for each section may be fired more than once during page printing you should not use it to do any totaling in which values are carried over from one section to another. However, you can use report variables to do calculated fields.

There are three formatting modes:

FormattingIdle | No formatting occurs. This can be before going to preview or print or between changing pages in the viewer.
FormattingActive | The start of formatting an object. The object mode is marked as formatting active.
FormattingInactive | When the print engine is formatting and one object is in FormattingActive mode the rest of the objects are in FormattingInactive mode.

Since there is only one section Format event when one section is formatting all of the objects in that section are in FormattingActive mode and all the rest of the sections and objects are in FormattingInactive mode.

Rules
  • The read property can be accessed in any formatting mode. (There are a few exceptions, please see the object model reference section.)
  • Top level Report, Areas and Area write properties and methods can only be accessed in formatting idle mode, aside from a few exceptions.
  • When in FormattingIdle mode you should make changes before going to preview or print. Making changes between changing pages may result in an unexpected result.
  • For sections and objects within sections write property or method access is denied when the section is in FormattingInactive mode.
  • For sections and objects within sections some write property or method access is permitted and some denied while the section is in FormattingActive mode. Please refer the object model reference for details.


Sections Collection

Sections can come from either the Report Object or Area Object. The Sections Collection is a collection of section objects. Access a specific Section Object in the collection using the Item property.

  • When from the Report Object, the sections object will contain all the sections in the report.
  • When from the Area Object, the sections object will contain all the sections in the area only.

Sections Collection Properties

Property | Description | Read/ Write | Restriction in event handler
Count | Long. Gets the number of section in the collection. | Read only | None
Item (index) | Section Object. Gets reference to an item in the Collection. Item has an index parameter that can be either a string reference to the area section (i.e., for areas with one section: "RH", "PH", "GHn", "D", "GFn", "PF", or "RF") or a numeric, 1-based index (i.e., Item (1)) for the Report Header area. Numeric index for sections starts at 1 for first section in the area/report and continues in order of appearance. If the area has multiple sections, they are represented using a lowercase letter (for example, "Da", "Db", etc.). | Read only | None
Parent | Report Object or Area Object. Gets reference to the parent object. | Read only | None

Remarks

Instead of using the Item property as shown, you can reference a section directly, for example, Sections ("Da").


Sections Collection Methods

The following methods are discussed in this section:

Add Method (Sections Collection)

Delete Method (Sections Collection)


Add Method (Sections Collection)

Use Add method to add a Section Object to the Sections Collection.

Syntax

Function Add ([index]) As Section

Parameter

Parameter | Description
[index] | Specifies the index where you would like to add the Section to the Collection.

Returns

Returns a Section Object member of the Sections Collection.


Delete Method (Sections Collection)

Use Delete method to remove a Section Object from the Sections Collection.

Syntax

Sub Delete(index)

Parameter

Parameter | Description
index | Specifies the index of the Section that you want to delete from the Collection.


SortField Object

The SortField Object includes properties for accessing information for record or group sort fields. It holds on to Report object, then releases the report object when destroyed. This object has an index instance variable to indicate its index.

SortField Object Properties

Property | Description | Read/Write | Restriction in event handler
Field | Object. Gets or sets the sorting field definition object. | Read/Write | Can be read or written only when formatting idle.
Parent | Report Object. Gets reference to the parent object. | Read only | None
SortDirection | CRSortDirection. Gets or sets the sort direction. | Read/Write | Can be written only when formatting idle.


SortFields Collection

The SortFields Collection is a collection of sort fields; can be either record sort field or group sort field. Access a specific SortField Object in the collection using the Item property.

SortFields Collection Properties

Property | Description | Read/ Write | Restriction in event handler
Count | Long. Gets the number of sort fields in the collection. | Read only | None
Item (index As Long) | SortField Object. Gets reference to an item in the Collection. Item has an index parameter that is a numeric, 1-based index (that is, Item (1)). The sort fields in the collection are indexed in the order they were added as sort fields to the report. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None

Remarks

Instead of using the Item property as shown, you can reference a sort field directly, for example, SortFields(1).


SortFields Collection Methods

The following methods are discussed in this section:

Add Method (SortFields Collection)

Delete Method (SortFields Collection)


Add Method (SortFields Collection)

The Add method adds a record or group sort field to the Collection.

Syntax
Sub Add (pFieldDefinition As IFieldDefinition,

    SortDirection As CRSortDirection)
Parameters

Parameter | Description
pFieldDefinition | FieldDefinition Object. Specifies the field definition or field name.
SortDirection | CRSortDirection. Specifies the direction in which the field data should be sorted (that is, ascending, descending, etc.).


Delete Method (SortFields Collection)

The Delete method deletes a record or group sort field from the Collection.

Syntax

Sub Delete (index As Long)

Parameter

Parameter | Description
index | Specifies the 1-based index number of the sort field in the collection that you want to delete.


SpecialVarFieldDefinition Object

The SpecialVarFieldDefinition Object provides properties for retrieving information and setting options for a special field found in your report (i.e., last modification date, print date, etc.). A SpecialVarFieldDefinition Object is obtained from the Field property of the FieldObject Object.

SpecialVarFieldDefinition Object Properties

Property | Description | Read/Write | Restriction in event handler
Kind | CRFieldKind. Gets which kind of field (database, summary, formula, etc.). | Read only | None
Name | String. Gets the field definition unique formula name of the special var. field. | Read only | None
NextValue | Variant. Gets the field next value. | Read only | Can be read only when top-level Report object is formatting active.
NumberOfBytes | Integer. Gets the number of bytes required to store the field data in memory. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None
PreviousValue | Variant. Gets the field previous value. | Read only | Can be read only when top-level Report object is formatting active.
SpecialVarType | CRSpecialVarType. Gets what the type of special field (for example, ReportTitle, PageNumber, etc.). | Read only | None
Value | Variant. Gets the field current value. | Read only | Can be read only when top-level Report object is formatting active.
ValueType | CRFieldValueType. Gets which type of value is found in the field. | Read only | None


SQLExpressionFieldDefinition Object

The SQLExpressionFieldDefinition Object represents a SQL expression field used in the report. This object provides properties for getting information on SQL expression fields in the report.

SQLExpressionFieldDefinition Object Properties

Property | Definition | Read/Write | Restriction in event handler
Kind | CRFieldKind. Gets which kind of field (that is, database, summary, formula, etc.). | Read only | None
Name | String. Gets the field definition unique formula name of the field within the report, Crystal formula syntax. | Read only | None
NextValue | Variant. Gets the field next value. | Read only | Can be read only when top-level Report object is formatting active.
NumberOfBytes | Integer. Gets the number of bytes required to store the field data in memory. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None
PreviousValue | Variant. Gets the field previous value. | Read only | Can be read only when top-level Report object is formatting active.
SQLExpression FieldName | String. Gets the SQL expression field name. | Read only | None
Text | String. Gets or sets the SQL expression text. | Read/Write | Can be written only when formatting idle.
Value | Variant. Gets the field current value. | Read only | Can be read only when top-level Report object is formatting active.
ValueType | CRFieldValueType. Gets which type of value is found in the field. | Read only | None


SQLExpressionFieldDefinition Object Methods

The following method is discussed in this section:

Check Method (SQLExpressionFieldDefinition Object)


Check Method (SQLExpressionFieldDefinition Object)

Use Check method to check whether a SQL expression is valid.

Syntax

Sub Check (pBool As Boolean, ppErrorString As String)

Parameters

Parameter | Description
pBool | Boolean value indicating the condition of the formula string. Will be set to TRUE if the formula is valid and FALSE if the formula contains one or more errors.
ppErrorString | Specifies the error message string if the formula contains an error.


SQLExpressionFieldDefinitions Collection

The SQLExpressionFieldDefinitions Collection is a collection of SQL expression field definition objects. One object exists in the collection for every SQL expression field accessed by the report. Access a specific SQLExpressionFieldDefinition Object in the collection using the Item property.

SQLExpressionFieldDefinitions Collection Properties

Property | Description | Read/Write | Restriction in event handler
Count | Long. Gets the number of items in the Collection. | Read only | None
Item (index As Long) | SQLExpressionFieldDefinition Object. Gets an item from the Collection. Item has an index parameter that is a 1-based index (that is, Item (1) for the first SQL Expression field in the collection). The items in the collection are indexed in the order they were added to the report. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None

Remarks

Instead of using the Item property as shown, you can reference a database directly, for example, SQLExpressionFieldDefinitions(1).


SQLExpressionFieldDefinitions Collection Methods

The following methods are discussed in this section:

Add Method (SQLExpressionFieldDefinitions Collection)

Delete Method (SQLExpressionFieldDefinitions Collection)


Add Method (SQLExpressionFieldDefinitions Collection)

Use Add method to add a SQLExpressionFieldDefinition Object to the Collection.

Syntax
Function Add (SQLExpressionName As String,

    Text As String) As SQLExpressionFieldDefinition
Parameters

Parameter | Description
SQLExpressionName | Specifies the name of the SQL expression that you want to add to the Collection.
Text | Specifies the text of the SQL expression that you want to add to the Collection.

Returns

Returns a SQLExpressionFieldDefinition Object member of the Collection.


Delete Method (SQLExpressionFieldDefinitions Collection)

Use Delete method to remove a SQLExpressionFieldDefinition Object from the Collection.

Syntax

Sub Delete (index)

Parameter

Parameter | Description
index | Specifies the index number of the SQLExpressionFieldDefinition Object that you want to remove from the Collection.


SubreportLink Object

The SubreportLink Object provides information about Subreport Links to the main report.

SubreportLink Object Properties

Property | Description | Read/Write | Restriction in event handler
MainReportField | FieldDefinition Object. Gets the main report field to which the subreport field is linked. | Read only | None
Parent | SubreportObject Object. Gets the subreport link's parent object. | Read only | None
SubReportField | FieldDefinition Object. Gets the subreport field. | Read only | None


SubreportLinks Collection

The SubreportLinks Collection contains the SubreportLink Object related to the report.

SubreportLinks Collection Properties

Property | Description | Read/Write | Restriction in event handler
Count | Long. Gets a count of the items in the Collection. | Read only | None
Item (index As Long) | SubreportLink Object. Gets an item from the Collection. | Read only | None
Parent | SubreportObject Object. Gets reference to the subreport link's parent object. | Read only | None


SubreportLinks Collection Methods

The following methods are discussed in this section:

Add Method (SubreportLinks Collection)

Delete Method (SubreportLinks Collection)


Add Method (SubreportLinks Collection)

Use Add method to add a SubreportLink Object to the Collection.

Syntax

Function Add (MainReportField, SubreportField) As SubreportLink

Parameters

Parameter | Description
MainReportField | Specifies the field in the main report that you want the new Object in the Collection to link.
SubreportField | Specifies the field in the subreport that you want the new Object in the Collection to link.

Returns

Returns a SubreportLink Object member of the Collection.


Delete Method (SubreportLinks Collection)

Use Delete method to remove a SubreportLink Object from the Collection.

Syntax

Sub Delete (index As Long)

Parameter

Parameter | Description
index | Specifies the index number of the Object in the Collection that you want to remove.


SubreportObject Object

The SubreportObject Object represents a subreport placed in a report. A subreport is a free-standing or linked report found within the main report. This object provides properties for retrieving information on the subreport (for example, name, formatting options, etc.).

SubreportObject Object Properties

Property | Description | Read/Write | Restriction in event handler
BackColor | OLE_COLOR. Gets or sets the object background color. | Read/Write | Can be written only when formatting idle or active.
BorderColor | OLE_COLOR. Gets or sets the object border color. | Read/Write | Can be written only when formatting idle or active.
BottomLineStyle | CRLineStyle. Gets or sets the bottom line style. | Read/Write | Can be written only when formatting idle or active.
CanGrow | Boolean. Gets or sets the can grow option. | Read/Write | Can be written only when formatting idle or active.
CloseAtPage Break | Boolean. Gets or sets close border on page break. | Read/Write | Can be written only when formatting idle or active.
EnableOn Demand | Boolean. Gets the real-time subreport option. | Read only | None
HasDropShadow | Boolean. Gets or sets the border drop shadow option. | Read/Write | Can be written only when formatting idle or active.
Height | Long. Gets or sets the object height, in twips. | Read/Write | Can be written only when formatting idle or active.
KeepTogether | Boolean. Gets or sets the keep object together option. | Read/Write | Can be written only when formatting idle or active.
Kind | CRObjectKind. Gets what kind of object (for example, box, cross-tab, field). | Read only | None
Left | Long. Gets or sets the object upper left position, in twips. | Read/Write | Can be written only when formatting idle or active.
LeftLineStyle | CRLineStyle. Gets or sets the left line style. | Read/Write | Can be written only when formatting idle or active.
Links | SubreportLinks Collection. Gets reference to the Collection. | Read Only | None
Name | String. Gets or sets the object name. | Read/Write | Can be written only when formatting idle or active.
Parent | Section Object. Gets reference to the parent object. | Read only | None
RightLineStyle | CRLineStyle. Gets or sets the right line style. | Read/Write | Can be written only when formatting idle or active.
SubreportName | String. Gets or sets the name of the subreport. | Read/Write | Can be written only when formatting idle.
Suppress | Boolean. Gets or sets the object visibility option. | Read/Write | Can be written only when formatting idle or active.
Top | Long. Gets or sets the object upper top position, in twips. | Read/Write | Can be written only when formatting idle or active.
TopLineStyle | CRLineStyle. Gets or sets the top line style. | Read/Write | Can be written only when formatting idle or active.
Width | Long. Gets or sets the object width, in twips. | Read/Write | Can be written only when formatting idle or active.


SubreportObject Object Methods

The following methods are discussed in this section:

OpenSubreport Method (SubreportObject Object)


OpenSubreport Method (SubreportObject Object)

Every subreport has a pointer to its parent report. Subreports hold on to their parent reports until they are destroyed. The OpenSubreport method opens a subreport contained in the report and returns a Report Object corresponding to the named subreport. It corresponds to PEOpenSubreport of the Crystal Report Engine. This method can be invoked only in FormattingIdle or FormattingActive mode.

Syntax

Function OpenSubreport () As Report

Returns

Returns a SubreportObject Object.


ReImportSubreport Method (Subreport Object)

Subreports can be newly created in the main report or imported from an existing report file. If the subreport is imported from an existing report file, it can be re-imported at runtime using the ReImportSubreport method. When previewed, printed, or exported, a re-imported subreport will reflect all changes made to the formatting, grouping, and structure of the existing report file.

Syntax

Sub ReImportSubreport (pReimported as Boolean)

Parameter

Parameter | Description
pReimported | Boolean value indicating success or failure when re-importing the subreport. Will be set to TRUE if re-importing the subreport succeeds and FALSE if re-importing the subreport fails.See remarks below.

Remarks

pReimported is an output parameter. Create a variable to hold the result of pReimported and check the value of the variable to see if the method is successful.

Sample

'Boolean value to hold the result of the ReimportSubreport method
Dim bReimported As Boolean

'Call ReImportSubReport
Report.Subreport1.ReimportSubreport bReimported

'If bReimported is True the subreport re-imported successfully
'If bReimported is False the subreport failed to re-import
If bReimported Then
    MsgBox "Subreport re-imported successfully"
Else
    MsgBox "Subreport failed to re-import"
    Exit Sub
End If

'Refresh the viewer to display the updated subreport.
'Set the parameter to True if you want to update the data
'or False if you only want to refresh the report
CRViewer1.RefreshEx False


SummaryFieldDefinition Object

The SummaryFieldDefinition Object represents the summary used in a cross-tab, group, or report.

SummaryFieldDefinition Object Properties

Property | Description | Read/ Write | Restriction in event handler
FooterArea | Area Object. Gets the area pair that the summary is in. | Read only | None
ForCrossTab | Boolean. Gets for-cross-tab. | Read only | None
HeaderArea | Area Object. Gets the area pair that the summary is in. | Read only | None
Hierarchical SummaryType | CRHierarchicalSummaryType. Gets or sets wether or not to calculate the summary across the hierarchy in a hierarchically grouped report. | Read/Write | Can be written only when formatting idle.
Kind | CRFieldKind. Gets which kind of field (database, summary, formula, etc.). | Read only | None
Name | String. Gets the field definition unique formula name of the summary field for a group or report summary field. Cross-tab summaries do not have a unique name so an empty string will be returned. | Read only | None
NextValue | Variant. Gets the field next value. | Read only | Can be read only when top-level Report object is formatting.
NumberOfBytes | Integer. Gets the number of bytes required to store the field data in memory. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None
PreviousValue | Variant. Gets the field previous value. | Read only | Can be read only when top-level Report object is formatting.
Secondary SummarizedField | Object. Gets the secondary summarized field. | Read only | None
SummarizedField | Object. Gets the summarized field. | Read only | None
SummaryOperationParameter | Long. Gets or sets the summary operation parameter. | Read/Write | Can be written only when formatting idle.
SummaryType | CRSummaryType. Gets or sets the type of summary (for example, sum, average, etc.). | Read/Write | Can be written only when formatting idle.
Value | Variant. Gets the field current value. | Read only | Can be read only when top-level Report object is formatting active.
ValueType | CRFieldValueType. Gets which type of value is found in the field. | Read only | None


SummaryFieldDefinition Object Methods

The following methods are discussed in this section:

SetSecondarySummarizedField Method (SummaryFieldDefinition Object)

SetSummarizedField Method (SummaryFieldDefinition Object)


SetSecondarySummarizedField Method
(SummaryFieldDefinition Object)

Use SetSecondarySummarizedField method to set the secondary summarized field for a report.

Syntax
Sub SetSecondarySummarizedField (secondarySummariedField)
Parameter

Parameter | Description
secondarySummariedField | Specifies the field that you want to set.


SetSummarizedField Method (SummaryFieldDefinition Object)

Syntax

Sub SetSummarizedField (SummarizedField)

Parameter

Parameter | Description
SummarizedField | Specifies the field that you want to set.


SummaryFieldDefinitions Collection

The SummaryFieldDefinitions Collection is a collection of summary field definitions. Can be from either CrossTabObject Object or Report Object. Access a specific SummaryFieldDefinition Object in the collection using the Item property.

SummaryFieldDefinitions Collection Properties

Property | Description | Read/Write | Restriction in event handler
Count | Long. Gets the number of summary fields in the collection. | Read only | None
Item (index As Long) | SummaryFieldDefinition Object. Gets an item from the Collection. Item has an index parameter that is a numeric, 1-based index (for example, Item (1)). The items in the collection are indexed in the order they were added to the report. | Read only | None
Parent | Report Object. Gets reference to the parent object. | Read only | None

Remarks

Instead of using the Item property as shown, you can reference a summary field directly, for example, SummaryFieldDefinitions(1).


SummaryFieldDefinitions Collection Methods

The following methods are discussed in this section:

Add Method (SummaryFieldDefinitions Collection)

Delete Method (SummaryFieldDefinitions Collection)


Add Method (SummaryFieldDefinitions Collection)

Use Add method to add a SummaryFieldDefinition Object to the Collection.

Syntax
Function Add (groupLevel As Long, Field,

    SummaryType As CRSummaryType, [secondSummaryFieldOrFactor]

    ) As SummaryFieldDefinition
Parameters

Parameter | Description
groupLevel | Specifies the group level for the summary.
Field | Specifies the summary field.
SummaryType | CRSummaryType. Specifies the summary type.
[secondSummaryFieldOr Factor] | Specifies the second summary field or factor.

Returns

Returns a SummaryFieldDefinition Object member of the Collection.


Delete Method (SummaryFieldDefinitions Collection)

Use delete method to delete a SummaryFieldDefinition Object from the Collection.

Syntax

Sub Delete (index)

Parameter

Parameter | Description
index | Specifies the index number of the object that you want to delete from the Collection.


TableLink Object

The TableLink Object provides information about database table links.

TableLink Object Properties

Property | Description | Read/Write | Restriction in event handler
DestinationFields | DatabaseFieldDefinitions Collection. Gets reference to table link destination field definitions Collection. | Read only | None
DestinationTable | DatabaseTable Object. Gets reference to the table link destination table. | Read only | None
IndexUsed | Integer. Gets table link IndexUsed | Read only | None
JoinType | CRLinkJoinType. Gets the table link join type. | Read only | None
LookupType | CRLinkLookUpType. Gets table link lookup type. | Read only | None
Parent | Database Object. Gets reference to the parent object. | Read only | None
PartialMatch Enabled | Boolean. Gets the table link partial-match enabled option. | Read only | None
SourceFields | DatabaseFieldDefinition Object. Gets the table link source field definitions. | Read only | None
SourceTable | DatabaseTable Object. Gets table link source table. | Read only | None


TableLinks Collection

The TableLinks Collection contains the TableLink Object Objects associated with the report.

TableLinks Collection Properties

Property | Definition | Read/ Write | Restriction in event handler
Count | Long. Gets a count of the collection items. | Read only | None
Item (index As Long) | TableLink Object. Gets an item from the Collection. | Read only | None
Parent | Database Object. Gets reference to the parent object. | Read only | None


TableLinks Collection Methods

The following methods are discussed in this section:

Add Method (TableLinks Collection)

Delete Method (TableLinks Collection)


Add Method (TableLinks Collection)

Use Add method to add a TableLink Object to the Collection.

Syntax
Function Add (psrcTable As DatabaseTable, pDestTable As DatabaseTable,

    srcFields, destFields,

    JoinType As CRLinkJoinType, LookupType As CRLinkLookUpType,

    PartialMatchEnabled As Boolean, indexInUse As Integer) As TableLink
Parameters

Parameter | Description
psrcTable | DatabaseTable Object. Specifies the source database table.
pDestTable | DatabaseTable Object. Specifies the destination database table.
srcFields | Specifies the source fields.
destFields | Specifies th destination fields.
JoinType | CRLinkJoinType. Specifies the link join type.
LookupType | CRLinkLookUpType. Specifies the link lookup type.
PartialMatchEnabled | Specifies whether the PartialMatchEnabled option has been set.
indexInUse | Specifies index in use.

Returns

Returns a TableLink Object member of the Collection.


Delete Method (TableLinks Collection)

Use Delete method to remove a TableLink Object from the Collection.

Syntax

Sub Delete (index As Long)

Parameter

Parameter | Description
index | Specifies the index number of the item that you want to remove from the Collection.


TextObject Object

The Text Object represents a text object found in a report. This object provides properties for retrieving information and setting options for a text object in your report.

TextObject Object Properties

Property | Description | Read/Write | Restriction in event handler
BackColor | OLE_COLOR. Gets or sets the object background color. | Read/Write | Can be written only when formatting idle or active.
BorderColor | OLE_COLOR. Gets or sets the object border color. | Read/Write | Can be written only when formatting idle or active.
BottomLineStyle | CRLineStyle. Gets or sets the bottom line style. | Read/Write | Can be written only when formatting idle or active.
CanGrow | Boolean. Gets or sets the can grow option. | Read/Write | Can be written only when formatting idle or active.
CharacterSpacing | Long. Gets or sets the character spacing. | Read/Write | Can be written only when formatting idle.
CloseAtPage Break | Boolean. Gets or sets th close border on page break option. | Read/Write | Can be written only when formatting idle or active.
FirstLineIndent | Long. Gets or sets first line indent, in twips. | Read/Write | Can be written only when formatting idle.
Font | IFontDisp. Gets or sets the standard OLE font of the text object. | Read/Write | Can be written only when formatting idle or active.
HasDropShadow | Boolean. Gets or sets the border drop shadow option. | Read/Write | Can be written only when formatting idle or active.
Height | Long. Gets or sets the object height, in twips. | Read/Write | Can be written only when formatting idle or active.
HorAlignment | CRAlignment. Gets or sets the horizontal alignment. | Read/Write | Can be written only when formatting idle.
KeepTogether | Boolean. Gets or sets the keep area together option. | Read/Write | Can be written only when formatting idle or active.
Kind | CRObjectKind. Gets what kind of object (for example, box, cross-tab, field). | Read only | None
Left | Long. Gets or sets the object upper left position, in twips. | Read/Write | Can be written only when formatting idle or active.
LeftIndent | Long. Gets or sets left indent. | Read/Write | Can be written only when formatting idle.
LeftLineStyle | CRLineStyle. Gets or sets the left line style. | Read/Write | Can be written only when formatting idle or active.
LineSpacing | Double. Gets the line spacing. | Read only | Can be written only when formattin idle.
LineSpacingType | CRLineSpacingType. Gets the line spacing type. | Read only |
MaxNumberOf Lines | Integer. Gets or sets the maximum number of line for a string memo field. | Read/Write | Can be written only when formatting idle or active.
Name | String. Gets or sets area name. | Read/Write | Can be written only when formatting idle.
Parent | Section Object. Gets reference to the parent object. | Read only | None
RightIndent | Long. Gets or sets the right indent. | Read/Write | Can be written only when formatting idle.
RightLineStyle | CRLineStyle. Gets or sets the right line style. | Read/Write | Can be written only when formatting idle or active.
Suppress | Boolean. Gets or sets object visibility. | Read/Write | Can be written only when formatting idle or active.
SuppressIf Duplicated | Boolean. Gets or sets the suppress if duplicated option. | Read/Write | Can be written only when formatting idle or active.
Text | String. Gets the text within the text object. If it has embedded fields, [] is used to represent the embedded field. | Read only | None
TextColor | OLE_COLOR. Gets or sets the object text color. | Read/Write | Can be written only when formatting idle.
TextRotation Angle | CRRotationAngle. Gets or sets text rotation angle. | Read/Write | Can be written only when formatting idle.
Top | Long. Gets or sets the object upper top position, in twips. | Read/Write | Can be written only when formatting idle or active.
TopLineStyle | CRLineStyle. Gets or sets the top line style. | Read/Write | Can be written only when formatting idle or active.
Width | Long. Gets or sets the object width, in twips. | Read/Write | Can be written only when formatting idle or active.


TextObject Object Methods

The following methods are discussed in this section:

SetLineSpacing Method (TextObject Object)

SetLineSpacing Method (TextObject Object)


SetLineSpacing Method (TextObject Object)

Use the SetLineSpacing method to set the line spacing for a TextObject Object. The information passed will be used during formatting.

Syntax
Sub SetLineSpacing (LineSpacing As Double,

    LineSpacingType As CRLineSpacingType)
Parameters

Parameter | Description
LineSpacing | Specifies the line spacing.
LineSpacingType | CRLineSpacingType. Specifies the line spacing type.


SetText Method (TextObject Object)

Use the SetText method to set the text object to return the specified text. This method can be invoked only in the FormattingIdle or FormattingActive mode.

Syntax

Sub SetText (pText As String)

Parameter

Parameter | Description
pText | Specifies the text string for the Object. See Remarks below.

Remarks

When the SetText method is called within the sections Format event handler, the text parameter passed should not be dependent upon some state that the event handler may be tracking. For example, the event handler may hold a count and increment it each time the Format event is fired. This could should not be used directly or indirectly to create the SetText text parameter.


Enumerated Types

CRAlignment

Constant | Value
crDefaultAlign | 0
crHorCenterAlign | 2
crJustified | 4
crLeftAlign | 1
crRightAlign | 3


CRAMPMType

Constant | Value
crAmPmAfter | 1
crAmPmBefore | 0


CRAreaKind

Constant | Value
crDetail | 4
crGroupFooter | 5
crGroupHeader | 3
crPageFooter | 7
crPageHeader | 2
crReportFooter | 8
crReportHeader | 1


CRBarSize

Constant (numeric order) | Description
crMinimumBarSize | 0
crSmallBarSize | 1
crAverageBarSize | 2
crLargeBarSize | 3
crMaximumBarSize | 4


CRBindingMatchType

Constant | Value
crBMTName | 0
crBMTNameAndValue | 1


CRBooleanOutputType

Constant | Value
crOneOrZero | 4
crTOrF | 1
crTrueOrFalse | 0
crYesOrNo | 2
crYOrN | 3


CRConvertDateTimeType

Constant | Value
crConvertDateTimeToDate | 1
crConvertDateTimeToString | 0
crKeepDateTimeType | 2


CRCurrencyPositionType

Constant | Value
crLeadingCurrencyInsideNegative | 0
crLeadingCurrencyOutsideNegative | 1
crTrailingCurrencyInsideNegative | 2
crTrailingCurrencyOutsideNegative | 3


CRCurrencySymbolType

Constant | Value
crCSTFixedSymbol | 1
crCSTFloatingSymbol | 2
crCSTNoSymbol | 0


CRDatabaseType

Constant | Value
crSQLDatabase | 2
crStandardDatabase | 1


CRDateCalendarType

Constant | Value
crGregorianCalendar | 1
crGregorianUSCalendar | 2
crHijriCalendar | 6
crJapaneseCalendar | 3
crKoreanCalendar | 5
crTaiwaneseCalendar | 4
crThaiCalendar | 7


CRDateEraType

Constant | Value
crLongEra | 1
crNoEra | 2
crShortEra | 0


CRDateOrder

Constant | Value
crDayMonthYear | 1
crMonthDayYear | 2
crYearMonthDay | 0


CRDateWindowsDefaultType

Constant | Value
crNotUsingWindowsDefaults | 2
crUseWindowsLongDate | 0
crUseWindowsShortDate | 1


CRDayType

Constant | Value
crLeadingZeroNumericDay | 1
crNoDay | 2
crNumericDay | 0


CRDiscreteOrRangeKind

Constant (numeric order) | Value
crDiscreteValue | 0
crRangeValue | 1
crDiscreteAndRangeValue | 2


CRDivisionMethod

Constant | Value
crAutomaticDivision | 0
crManualDivision | 1


CRExchangeDestinationType

Constant | Value
crExchangeFolderType | 0
crExchangePostDocMessage | 1011


CRExportDestinationType

Constant | Value
crEDTApplication | 5
crEDTDiskFile | 1
crEDTEMailMAPI | 2
crEDTEMailVIM | 3
crEDTLotusDomino | 6
crEDTMicrosoftExchange | 4
crEDTNoDestination | 0


CRExportFormatType

Constant | Value
crEFTCharSeparatedValues | 7
crEFTCommaSeparatedValues | 5
crEFTCrystalReport | 1
crEFTCrystalReport70 | 33
crEFTDataInterchange | 2
crEFTExactRichText | 35
crEFTExcel50 | 21
crEFTExcel50Tabular | 22
crEFTExcel70 | 27
crEFTExcel70Tabular | 28
crEFTExcel80 | 29
crEFTExcel80Tabular | 30
crEFTExplorer32Extend | 25
crEFTHTML32Standard | 24
crEFTHTML40 | 32
crEFTLotus123WK1 | 12
crEFTLotus123WK3 | 13
crEFTLotus123WKS | 11
crEFTNoFormat | 0
crEFTODBC | 23
crEFTPaginatedText | 10
crEFTPortableDocFormat | 31
crEFTRecordStyle | 3
crEFTReportDefinition | 34
crEFTTabSeparatedText | 9
crEFTTabSeparatedValues | 6
crEFTText | 8
crEFTWordForWindows | 14
crEFTXML | 36


CRFieldKind

Constant | Value
crDatabaseField | 1
crFormulaField | 2
crGroupNameField | 5
crRunningTotalField | 7
crParameterField | 6
crSpecialVarField | 4
crSQLExpressionField | 8
crSummaryField | 3


CRFieldMappingType

Constant | Value
crAutoFieldMapping | 0
crEventFieldMapping | 2
crPromptFieldMapping | 1


CRFieldValueType

Constant | Value
crBitmapField | 17
crBlobField | 15
crBooleanField | 9
crChartField | 21
crCurrencyField | 8
crDateField | 10
crDateTimeField | 16
crIconField | 18
crInt16sField | 3
crInt16uField | 4
crInt32sField | 5
crInt32uField | 6
crInt8sField | 1
crInt8uField | 2
crNumberField | 7
crOleField | 20
crPersistentMemoField | 14
crPictureField | 19
crStringField | 12
crTimeField | 11
crTransientMemoField | 13
crUnknownField | 22


CRFormulaSyntax

Constant | Value
crBasicSyntaxFormula | 1
crCrystalSyntaxFormula | 0 Default value


CRGraphColor

Constant | Value
crBlackAndWhiteGraph | 1
crColorGraph | 0


CRGraphDataPoint

Constant | Value
crNone | 0
crShowLabel | 1
crShowValue | 2


CRGraphDataType

Constant | Value
crCrossTabGraph | 2
crDetailGraph | 1
crGroupGraph | 0


CRGraphDirection

Constant | Value
crHorizontalGraph | 0
crVerticalGraph | 1


CRGraphType

Constant | Value
crAbsoluteAreaGraph | 20
crDualAxisBubbleGraph | 91
crFaked3DAbsoluteAreaGraph | 23
crFaked3DPercentAreaGraph | 25
crFaked3DPercentBarGraph | 5
crFaked3DRegularPieGraph | 31
crFaked3DSideBySideBarGraph | 3
crFaked3DStackedAreaGraph | 24
crFaked3DStackedBarGraph | 4
crHighLowDualAxisGraph | 101 Obsolete.
crHighLowGraph | 100
crHighLowOpenCloseDualAxisGraph | 105 Obsolete.
crHighLowOpenCloseGraph | 104
crHighLowOpenDualAxisGraph | 103 Obsolete.
crHighLowOpenGraph | 102 Obsolete.
crLineGraphWithMarkers | 13
crMultipleDoughnutGraph | 41
crMultiplePieGraph | 32
crMultipleProportionalDoughnut Graph | 42
crMultipleProportionalPieGraph | 33
crPercentageLineGraph | 12
crPercentageLineGraphWithMarkers | 15
crPercentAreaGraph | 22
crPercentBarGraph | 2
crRadarDualAxisGraph | 82
crRegularBubbleGraph | 90
crRegularDoughnutGraph | 40
crRegularLineGraph | 10
crRegularPieGraph | 30
crRegularRadarGraph | 80
crSideBySideBarGraph | 0
crStackedAreaGraph | 21
crStackedBarGraph | 1
crStackedLineGraph | 11
crStackedLineGraphWithMarkers | 14
crStackedRadarGraph | 81
crThreeDCutCornersGraph | 53
crThreeDOctagonGraph | 52
crThreeDPyramidGraph | 51
crThreeDRegularGraph | 50
crThreeDSurfaceHoneycombGraph | 62
crThreeDSurfaceRegularGraph | 60
crThreeDSurfaceWithSidesGraph | 61
crUnknownGraph | 1000
crXyScatterDualAxisGraph | 71
crXyScatterDualAxisWithLabelsGraph | 73
crXyScatterGraph | 70
crXyScatterWithLabelsGraph | 72


CRGridlineType

Constant | Value
crMajorAndMinorGridlines | 3
crMajorGridlines | 2
crMinorGridlines | 1
crNoGridlines | 0


CRGroupCondition

Constant | Value
crGCAnnually | 7
crGCAnyValue | 14
crGCBiweekly | 2
crGCByAMPM | 18
crGCByHour | 17
crGCByMinute | 16
crGCBySecond | 15
crGCDaily | 0
crGCEveryNo | 11
crGCEveryYes | 10
crGCMonthly | 4
crGCNextIsNo | 13
crGCNextIsYes | 12
crGCQuarterly | 5
crGCSemiAnnually | 6
crGCSemimonthly | 3
crGCToNo | 9
crGCToNo | 8
crGCWeekly | 1


CRHierarchicalSummaryType

Constant | Value
crHierarchicalSummaryNone | 0
crSummaryAcrossHierarchy | 1


CRHourType

Constant | Value
Const crNoHour | 2
Const crNumericHour | 0
Const crNumericHourNoLeadingZero | 1


CRHTMLPageStyle

Constant | Value
crFramePageStyle | 2
crPlainPageStyle | 0
crToolbarAtBottomPageStyle | 4
crToolbarAtTopPageStyle | 3
crToolbarPageStyle | 1


CRHTMLToolbarStyle

These bitwise constants can be XOR'd to specify the toolbar style.

Constant | Value
crToolbarRefreshButton | 1
crToolbarSearchBox | 2


CRImageType

Constant | Value
crDIBImageType | 1
crJPEGImageType | 2


CRLeadingDayPosition

Constant | Value
crLeadingDayOfWeek | 0
crTrailingDayOfWeek | 1


CRLeadingDayType

Constant | Value
crLongLeadingDay | 1
crNoLeadingDay | 2
crShortLeadingDay | 0


CRLegendPosition

Constant | Value
crPlaceBottomCenter | 1
crPlaceLeft | 4
crPlaceRight | 3
crPlaceTopCenter | 2
crPlaceUpperRight | 0


CRLineSpacingType

Constant | Value
crExactSpacing | 1
crMultipleSpacing | 0


CRLineStyle

Constant | Value
crLSDashLine | 3
crLSDotLine | 4
crLSDoubleLine | 2. Not valid for LineObject.LineStyle and BoxObject.LineStyle.
crLSNoLine | 0. Not valid for LineObject.LineStyle and BoxObject.LineStyle.
crLSSingleLine | 1


CRLinkJoinType

Constant | Value
crJTEqual | 4
crJTGreaterOrEqual | 10
crJTGreaterThan | 8
crJTLeftOuter | 5
crJTLessOrEqual | 11
crJTLessThan | 9
crJTNotEqual | 12
crJTRightOuter | 6


CRLinkLookUpType

Constant | Value
crLTLookupParallel | 1
crLTLookupProduct | 2
crLTLookupSeries | 3


CRMarkerShape

Constant | Value
crCircleShape | 4
crDiamondShape | 5
crRectangleShape | 1
crTriangleShape | 8


CRMarkerSize

Constant | Value
crLargeMarkers | 4
crMediumLargeMarkers | 3
crMediumMarkers | 2
crMediumSmallMarkers | 1
crSmallMarkers | 0


CRMinuteType

Constant | Value
crNoMinute | 2
crNumericMinute | 0
crNumericMinuteNoLeadingZero | 1


CRMonthType

Constant | Value
crLeadingZeroNumericMonth | 1
crLongMonth | 3
crNoMonth | 4
crNumericMonth | 0
crShortMonth | 2


CRNegativeType

Constant | Value
crBracketed | 3
crLeadingMinus | 1
crNotNegative | 0
crTrailingMinus | 2


CRNumberFormat

Constant | Value
crCurrencyMillions | 12
crCurrencyNoDecimal | 3
crCurrencyThousands | 11
crCurrencyTwoDecimal | 4
crCustomNumberFormat | 8
crMillionsNoDecimal | 10
crNoDecimal | 0
crOneDecimal | 1
crPercentNoDecimal | 5
crPercentOneDecimal | 6
crPercentTwoDecimal | 7
crThousandsNoDecimal | 9
crTwoDecimal | 2


CRObjectKind

Constant | Value
crBlobFieldObject | 9
crBoxObject | 4
crCrossTabObject | 8
crFieldObject | 1
crGraphObject | 7
crLineObject | 3
crMapObject | 10
crOlapGridObject | 11
crOleObject | 6
crSubreportObject | 5
crTextObject | 2


CRPaperOrientation

Constant | Value
crDefaultPaperOrientation | 0
crLandscape | 2
crPortrait | 1


CRPaperSize

Constant | Value
crDefaultPaperSize | 0
crPaper10x14 | 16
crPaper11x17 | 17
crPaperA3 | 8
crPaperA4 | 9
crPaperA4Small | 10
crPaperA5 | 11
crPaperB4 | 12
crPaperB5 | 13
crPaperCsheet | 24
crPaperDsheet | 25
crPaperEnvelope10 | 20
crPaperEnvelope11 | 21
crPaperEnvelope12 | 22
crPaperEnvelope14 | 23
crPaperEnvelope9 | 19
crPaperEnvelopeB4 | 33
crPaperEnvelopeB5 | 34
crPaperEnvelopeB6 | 35
crPaperEnvelopeC3 | 29
crPaperEnvelopeC4 | 30
crPaperEnvelopeC5 | 28
crPaperEnvelopeC6 | 31
crPaperEnvelopeC65 | 32
crPaperEnvelopeDL | 27
crPaperEnvelopeItaly | 36
crPaperEnvelopeMonarch | 37
crPaperEnvelopePersonal | 38
crPaperEsheet | 26
crPaperExecutive | 7
crPaperFanfoldLegalGerman | 41
crPaperFanfoldStdGerman | 40
crPaperFanfoldUS | 39
crPaperFolio | 14
crPaperLedger | 4
crPaperLegal | 5
crPaperLetter | 1
crPaperLetterSmall | 2
crPaperNote | 18
crPaperQuarto | 15
crPaperStatement | 6
crPaperTabloid | 3


CRPaperSource

Constant | Value
crPRBinAuto | 7
crPRBinCassette | 14
crPRBinEnvelope | 5
crPRBinEnvManual | 6
crPRBinFormSource | 15
crPRBinLargeCapacity | 11
crPRBinLargeFmt | 10
crPRBinLower | 2
crPRBinManual | 4
crPRBinMiddle | 3
crPRBinSmallFmt | 9
crPRBinTractor | 8
crPRBinUpper | 1


CRParameterFieldType

Constant | Value
crQueryParameter | 1
crReportParameter | 0
crStoreProcedureParameter | 2


CRParameterPickListSortMethod

Constant (numeric order) | Value
crNoSort | 0
crAlphanumericAscending | 1
crAlphanumericDescending | 2
crNumericAscending | 3
crNumericDescending | 4


CRPieLegendLayout

Constant | Value
crAmountLayout | 1
crCustomLayout | 2
crPercentLayout | 0


CRPieSize

Constant (numeric order) | Value
crMaximumPieSize | 0
crLargePieSize | 16
crAveragePieSize | 32
crSmallPieSize | 48
crMinimumPieSize | 64


CRPlaceHolderType

Constant | Value
crAllowPlaceHolders | 2
crDelayTotalPageCountCalc | 1


CRPrinterDuplexType

Constant | Value
crPRDPDefault | 0
crPRDPHorizontal | 3
crPRDPSimplex | 1
crPRDPVertical | 2


CRPrintingProgress

Constant | Value
crPrintingCancelled | 5
crPrintingCompleted | 3
crPrintingFailed | 4
crPrintingHalted | 6
crPrintingInProgress | 2
crPrintingNotStarted | 1


CRRangeInfo

Constant (numeric order) | Value
crRangeNotIncludeUpperLowerBound | 0
crRangeIncludeUpperBound | 1
crRangeIncludeLowerBound | 2
crRangeNoUpperBound | 4
crRangeNoLowerBound | 8


CRRenderResultType

Constant | Value
crBSTRType | 8. This constant is currently not supported.
crUISafeArrayType | 8209


CRReportFileFormat

Constant | Value
cr70FileFormat | 1792
cr80FileFormat | 2048


CRReportKind

Constant | Value
crColumnarReport | 1
crLabelReport | 2
crMulColumnReport | 3


CRReportVariableValueType

Constant | Value
crRVBoolean | 2
crRVCurrency | 1
crRVDate | 3
crRVDateTime | 5
crRVNumber | 0
crRVString | 6
crRVTime | 4


CRRotationAngle

Constant (numeric order) | Value
crRotate0 | 0
crRotate90 | 1
crRotate270 | 2


CRRoundingType

Constant (numeric order) | Value
crRoundToMillion | 17
crRoundToHundredThousand | 16
crRoundToTenThousand | 15
crRoundToThousand | 14
crRoundToHundred | 13
crRoundToTen | 12
crRoundToUnit | 11
crRoundToTenth | 10
crRoundToHundredth | 9
crRoundToThousandth | 8
crRoundToTenThousandth | 7
crRoundToHundredThousandth | 6
crRoundToMillionth | 5
crRoundToTenMillionth | 4
crRoundToHundredMillionth | 3
crRoundToBillionth | 2
crRoundToTenBillionth | 1


CRRunningTotalCondition

0
Constant | Value
crRTEvalNoCondition | 0
crRTEvalOnChangeOfField | 1
crRTEvalOnChangeOfGroup | 2
crRTEvalOnFormula | 3


CRSearchDirection

Constant (numeric order) | Value
crForward | 0
crBackward | 1


CRSecondType

Constant | Value
crNumericNoSecond | 2
crNumericSecond | 0
crNumericSecondNoLeadingZero | 1


CRSliceDetachment

Constant (numeric order) | Value
crLargestSlice | 2
crSmallestSlice | 1
crNoDetachment | 0


CRSortDirection

Constant | Value
crAscendingOrder | 0
crDescendingOrder | 1
crOriginalOrder | 2. Not supported for any kind of groups.
crSpecifiedOrder | 3. Not supported for any kind of groups.


CRSpecialVarType

Constant | Value
crSVTDataDate | 4
crSVTDataTime | 5
crSVTFileAuthor | 15
crSVTFileCreationDate | 16 (&H10)
crSVTFilename | 14
crSVTGroupNumber | 8
crSVTGroupSelection | 13
crSVTModificationDate | 2
crSVTModificationTime | 3
crSVTPageNofM | 17 (&H11)
crSVTPageNumber | 7
crSVTPrintDate | 0
crSVTPrintTime | 1
crSVTRecordNumber | 6
crSVTRecordSelection | 12
crSVTReportComments | 11
crSVTReportTitle | 10
crSVTTotalPageCount | 9


CRSummaryType

Constant | Value
crSTAverage | 1
crSTCount | 6
crSTDCorrelation | 10
crSTDCovariance | 11
crSTDistinctCount | 9
crSTDMedian | 13
crSTDMode | 17
crSTDNthLargest | 15
crSTDNthMostFrequent | 18
crSTDNthSmallest | 16
crSTDPercentage | 19
crSTDPercentile | 14
crSTDWeightedAvg | 12
crSTMaximum | 4
crSTMinimum | 5
crSTPopStandardDeviation | 8
crSTPopVariance | 7
crSTSampleStandardDeviation | 3
crSTSampleVariance | 2
crSTSum | 0


CRTableDifferences

Constant | Value
crTDOK | 0x00000000
crTDDatabaseNotFound | 0x00000001
crTDServerNotFound | 0x00000002
crTDServerNotOpened | 0x00000004
crTDAliasChanged | 0x00000008
crTDIndexesChanged | 0x00000010
crTDDriverChanged | 0x00000020
crTDDictionaryChanged | 0x00000040
crTDFileTypeChanged | 0x00000080
crTDRecordSizeChanged | 0x00000100
crTDAccessChanged | 0x00000200
crTDParametersChanged | 0x00000400
crTDLocationChanged | 0x00000800
crTDDatabaseOtherChanges | 0x00001000
crTDNumberFieldChanged | 0x00010000
crTDFieldOtherChanges | 0x00020000
crTDFieldNameChanged | 0x00040000
crTDFieldDescChanged | 0x00080000
crTDFieldTypeChanged | 0x00100000
crTDFieldSizeChanged | 0x00200000
crTDNativeFieldTypeChanged | 0x00400000
crTDNativeFieldOffsetChanged | 0x00800000
crTDNativeFieldSizeChanged | 0x01000000
crTDFieldDecimalPlacesChanged | 0x02000000


CRTextFormat

Constant | Value
crHTMLText | 2
crRTFText | 1
crStandardText | 0


CRTimeBase

Constant | Value
cr12Hour | 0
cr24Hour | 1


CRTopOrBottomNGroupSortOrder

Constant | Value
crAllGroupsSorted | 1
crAllGroupsUnsorted | 0
crBottomNGroups | 3
crTopNGroups | 2


CRValueFormatType

Constant | Value
crAllowComplexFieldFormatting | 4
crIncludeFieldValues | 1
crIncludeHiddenFields | 2


CRViewingAngle

Constant | Value
crBirdsEyeView | 15
crDistortedStdView | 10
crDistortedView | 4
crFewGroupsView | 9
crFewSeriesView | 8
crGroupEmphasisView | 7
crGroupEyeView | 6
crMaxView | 16
crShorterView | 12
crShortView | 5
crStandardView | 1
crTallView | 2
crThickGroupsView | 11
crThickSeriesView | 13
crThickStdView | 14
crTopView | 3


CRYearType

0
Constant | Value
crLongYear | 1
crNoYear | 2
crShortYear | 0


Report Viewer Object Model

The Crystal Report Viewer contains an extensive object model allowing you complete control over how the viewer appears and functions. This section provides detailed information on the properties, methods and events of the Crystal Report Viewer object model for both the ActiveX viewer, and the Java Bean viewer.

Click the appropriate link to jump to that section:

  • Report Viewer/ActiveX Object Model Technical Reference
  • Enumerated Types - Report Viewer
  • The Report Viewer/Java Bean Technical Reference


Report Viewer/ActiveX Object Model Technical Reference

The following diagram outlines the Report Viewer hierarchy.


CRField Object (CRVIEWERLib)

The CRField Object contains information related to the fields in a report displayed in the Report Viewer.

CRField Object Properties

Property | Description | Read/Write
FieldType | CRFieldType (CRViewerLib). Gets the type of field. | Read-only
IsRawData | Boolean. Gets whether or not the data in the field is raw data. | Read-only
Name | String. Gets the name of the field. | Read-only
Value | Variant. Default property gets the value in the field. | Read-only


CRFields Collection (CRVIEWERLib)

The CRFields Collection contains instances of CRFields Objects.

CRFields Collection Properties

Property | Description | Read/Write
Count | Long. Gets the total number of items in the Collection. | Read-only
Item (index As Long) | Long. Default property gets the 1-based index number of the item in the Collection. | Read-only
SelectedFieldIndex | Long. Gets the index of the selected field. | Read-only


CRVEventInfo Object (CRVIEWERLib)

The CRVEventInfo Object contains information about events relating to objects within a report.

CRVEventInfo Object Properties

Property | Description | Read/Write
CanDrillDown | Boolean. Gets whether or not the object is drillable. | Read-only
Index | Long. Gets or sets the number identifying a control in a control array. | Read-only
ParentIndex | Long. Gets reference to the object's parent's index. | Read-only
Text | String. Gets the object's text string. | Read-only
Type | CRObjectType (CRViewerLib). Gets the object type. | Read-only


CRVEventInfo Object Methods

The following methods are discussed in this section:

GetFields Method (CRVEventInfo Object)

GetFields Method (CRVEventInfo Object)

Use GetFields method to get the Fields Collection.

Syntax

Function GetFields ()


CRViewer Object (CRVIEWERLib)

The CRViewer Object is the primary object representing the Report Viewer control as it appears on a Form in your Visual Basic application. The current interface is ICrystalReportViewer3.

CRViewer Object Methods

CRViewer Object Events


CRViewer Object Properties

Property | Description | Read/Write
ActiveViewIndex | Integer. Gets the 1-based index of the current view (tab). | Read only
DisplayBackgroundEdge | Boolean. Gets or sets whether the report is offset from the edge of its view window. | Read/Write
DisplayBorder | Boolean. Gets or sets whether the border of the viewer object is displayed. | Read/Write
DisplayGroupTree | Boolean. Gets or sets the visibility of the group tree. | Read/Write
DisplayTabs | Boolean. Gets or sets whether the viewer has tabs for navigation between views. | Read/Write
DisplayToolbar | Boolean. Gets or sets the visibility of the toolbar. | Read/Write
EnableAnimationCtrl | Boolean. Gets or sets whether or not the animation control is visible. | Read/Write
EnableCloseButton | Boolean. Gets or sets the visibility of the close button. | Read/Write
EnableDrillDown | Boolean. Gets or sets whether drill down is allowed. | Read/Write
EnableExportButton | Boolean. Gets or sets the visibility of the Export toolbar button. | Read/Write
EnableGroupTree | Boolean. Gets or sets whether or not the group tree is available. | Read/Write
EnableHelpButton | Boolean. Gets or sets whether or not the help button appears on the toolbar. | Read/Write
EnableNavigationControls | Boolean. Gets or sets whether or not the First Page button, Previous Page button, Next Page button, and Last Page button appear on the toolbar. | Read/Write
EnablePopupMenu | Boolean. Gets or sets whether the popup menu is available. | Read/Write
EnablePrintButton | Boolean. Gets or sets the visibility of the Print button. | Read/Write
EnableProgressControl | Boolean. Gets or sets the visibility of the progress control. | Read/Write
EnableRefreshButton | Boolean. Gets or sets the visibility of the Refresh button. | Read/Write
EnableSearchControl | Boolean. Gets or sets the visibility of the search control. | Read/Write
EnableSearchExpertButton | Boolean. Gets or sets the status of the Search Expert toolbar button. | Read/Write
EnableStopButton | Boolean. Gets or sets whether the viewer displays the stop button. | Read/Write
EnableToolbar | Boolean. Gets or sets the visibility of the toolbar. | Read/Write
EnableZoomControl | Boolean. Gets or sets the visibility of the zoom control. | Read/Write
IsBusy | Boolean. Gets the status of the control, busy or not busy. | Read only
ReportSource | Unknown. Gets or sets the report source. | Read/Write
TrackCursorInfo | CRVTrackCursorInfo Object (CRVIEWERLib). Gets reference to TrackCursor information. | Read only
ViewCount | Integer. Gets the current number of views (tabs). | Read only


CRViewer Object Methods

The following methods are discussed in this section:

ActivateView Method (CRViewer Object)

AddView Method (CRViewer Object)

CloseView Method (CRViewer Object)

GetCurrentPageNumber Method (CRViewer Object)

GetViewName Method (CRViewer Object)

GetViewPath Method (CRViewer Object)

PrintReport Method (CRViewer Object)

Refresh Method (CRViewer Object)

SearchByFormula Method (CRViewer Object)

SearchForText Method (CRViewer Object)

ShowFirstPage Method (CRViewer Object)

ShowGroup Method (CRViewer Object)

ShowLastPage Method (CRViewer Object)

ShowNextPage Method (CRViewer Object)

ShowNthPage Method (CRViewer Object)

ShowPreviousPage Method (CRViewer Object)

ViewReport Method (CRViewer Object)

Zoom Method (CRViewer Object)


CRViewer Object Events

The following events are discussed in this section:

Clicked Event (CRViewer Object)

CloseButtonClicked Event (CRViewer Object)

DblClicked Event (CRViewer Object)

DownloadFinished Event (CRViewer Object)

DownloadStarted Event (CRViewer Object)

DrillOnDetail Event (CRViewer Object)

DrillOnGraph Event (CRViewer Object)

DrillOnGroup Event (CRViewer Object)

DrillOnSubreport Event (CRViewer Object)

ExportButtonClicked Event (CRViewer Object)

FirstPageButtonClicked Event (CRViewer Object)

GoToPageNClicked Event (CRViewer Object)

GroupTreeButtonClicked Event (CRViewer Object)

HelpButtonClicked Event (CRViewer Object)

LastPageButtonClicked Event (CRViewer Object)

NextPageButtonClicked Event (CRViewer Object)

OnReportSourceError Event (CRViewer Object)

PrevPageButtonClicked Event (CRViewer Object)

PrintButtonClicked Event (CRViewer Object)

RefreshButtonClicked Event (CRViewer Object)

SearchButtonClicked Event (CRViewer Object)

SearchExpertButtonClicked Event (CRViewer Object)

SelectionFormulaBuilt Event (CRViewer Object)

SelectionFormulaButtonClicked Event (CRViewer Object)

ShowGroup Event (CRViewer Object)

StopButtonClicked Event (CRViewer Object)

ViewChanged Event (CRViewer Object)

ViewChanging Event (CRViewer Object)

ZoomLevelChanged Event (CRViewer Object)


ActivateView Method (CRViewer Object)

Use ActivateView method to activate a particular view.

Syntax

Sub ActivateView ( Index )

Parameter

Parameter | Description
Index | The 1-based index number of the view that you want to activate.


AddView Method (CRViewer Object)

Use AddView method to add a new view tab to the Viewer.

Syntax

Sub AddView ( GroupPath )

Parameter

Parameter | Description
GroupPath | GroupPath can be a colon-delimited string (Country:State:City) or a safe array of strings. It indicates the group for which you want to add a view (tab) to the Report Viewer window.


CloseView Method (CRViewer Object)

Use CloseView method to close the specified view.

Syntax

Sub CloseView ( Index )

Parameter

Parameter | Description
Index | The 1- based index number of the view that you want to close.


GetCurrentPageNumber Method (CRViewer Object)

Use GetCurrentPageNumber method to retrieve the number of the page of the report that is currently being viewed.

Syntax

Function GetCurrentPageNumber () As Long

Returns

Returns the current page number, if the call is successful.


GetViewName Method (CRViewer Object)

Use GetViewName method to retrieve the current view's tab name and the current report document's name.

Syntax

Function GetViewName ( pTabName As String ) As String

Parameter

Parameter | Description
pTabName | Specifies the name of the current view (tab) As String.

Returns
  • Returns the current report's document name, if the call is successful.
  • Passes back the current view's tab name.


GetViewPath Method (CRViewer Object)

Use GetViewPath method to retrieve the path to the current view. Path contains a safe array of strings. Views refer to the main Preview Tab and drill down tabs that appear in the Report Viewer as the user interacts with the report.

Syntax

Function GetViewPath ( Index As Integer )

Parameter

Parameter | Description
Index | Specifies the 1-based index number of the view (tab) displayed in the Report Viewer for which you want to retrieve the path.

Returns

Returns a safe array of strings indicating the path to the current view, if the call is successful.

Example

Use the following code as an example of how to use GetViewPath.

Dim vPath As Variant

Dim vString As String

Dim x As Integer

Dim y As Integer

Dim counter As Integer

vPath = CRViewer1.GetViewPath(userEnteredInteger)

x = Lbound(vPath)

y = Ubound(vPath)

For counter = x To y

   If vString <> "" Then

      vString = vString & ":"

   End If

   vString = vString & vPath(counter)

Next counter

ViewPathName.Caption = "View path is: " & vString


PrintReport Method (CRViewer Object)

Use PrintReport method to initiate printing of the report in the current view.

Syntax

Sub PrintReport ()


Refresh Method (CRViewer Object)

Use Refresh method to reload and display the report displayed in the Report Viewer from its original source.

Syntax

Sub Refresh ()


SearchByFormula Method (CRViewer Object)

Use SearchByFormula method to search using the specified formula. The Search GUI is displayed if parameter formula is empty.

Syntax

Sub SearchByFormula ( formula As String )

Parameter

Parameter | Description
formula | Specifies the formula that you want to use for the search As String.


SearchForText Method (CRViewer Object)

Use SearchForText to search for the specified String.

Syntax

Sub SearchForText ( Text As String )

Parameter

Parameter | Description
Text | Specifies the text that you want to search for As String.


ShowFirstPage Method (CRViewer Object)

Use ShowFirstPage method to display the first page of the report.

Syntax

Sub ShowFirstPage ()


ShowGroup Method (CRViewer Object)

Use ShowGroup method to display the indicated group in the current view. GroupPath can be a colon-delimited string (Country:State:City) or a safe array of strings.

Syntax

Sub ShowGroup (GroupPath)

Parameter

Parameter | Description
GroupPath | Specifies the path to the group that you want to display. Use a safe array of strings or a colon delimited string (for example, Canada:BC:Vancouver).


ShowLastPage Method (CRViewer Object)

Use ShowLastPage method to display the last page of the report.

Syntax

Sub ShowLastPage ()


ShowNextPage Method (CRViewer Object)

Use ShowNextPage method to display the next page of the report.

Syntax

Sub ShowNextPage ()


ShowNthPage Method (CRViewer Object)

Use ShowNthPage method to display the specified page of the report.

Syntax

Sub ShowNthPage ( PageNumber As Integer )

Parameter

Parameter | Description
PageNumber | The page number that you want to display As Integer.


ShowPreviousPage Method (CRViewer Object)

Use ShowPreviousPage method to display the previous page of the report.

Syntax

Sub ShowPreviousPage ()


ViewReport Method (CRViewer Object)

Use ViewReport method to display the report.

Syntax

Sub ViewReport ()


Zoom Method (CRViewer Object)

Use Zoom method to change the magnification used to display the report.

Syntax

Sub Zoom ( ZoomLevel As Integer )

Parameter

Parameter | Description
ZoomLevel | The zoom level to use to view the report As Integer. Indicate a percentage, or use 1 to fit the entire width of the page in the Report Viewer window (but not the entire page) or 2 to fit the entire page in the window.


Clicked Event (CRViewer Object)

The Clicked event occurs when an object in the viewer is clicked.

Syntax

Event Clicked ( x As Long, y As Long, EventInfo, UseDefault As Boolean )

Parameters

Parameter | Description
X | Long. The X coordinate of the object clicked.
Y | Long. The Y coordinate of the object clicked.
EventInfo | A CRVEventInfo Object (CRVIEWERLib), containing information about the object clicked.
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


CloseButtonClicked Event (CRViewer Object)

The CloseButtonClicked event occurs when the Close Current View button is clicked.

Syntax

Event CloseButtonClicked ( UseDefault As Boolean )

Parameter

Parameter | Description
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


DblClicked Event (CRViewer Object)

The DblClicked event occurs when an object is double clicked.

Syntax

Event DblClicked ( x As Long, y As Long, EventInfo, UseDefault As Boolean )

Parameters

Parameter | Description
X | Long. The X coordinate of the object that was double clicked.
Y | Long. The Y coordinate of the object that was double clicked.
EventInfo | A CRVEventInfo Object (CRVIEWERLib), containing information about the object clicked.
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


DownloadFinished Event (CRViewer Object)

The DownloadFinished event occurs when report data finishes loading into the report. For example, if the user displays a new page, a new set of report data is downloaded.

Syntax

Event DownloadFinished ( loadingType As CRLoadingType )

Parameter

Parameter | Description
LoadingType | CRLoadingType (CRViewerLib). Indicates the type of data being loaded into the Report Viewer.


DownloadStarted Event (CRViewer Object)

The DownloadStarted event occurs when report data starts being downloaded into the Report Viewer. For example, if the user displays a new page, a new set of report data is downloaded.

Syntax

Event DownloadStarted ( loadingType As CRLoadingType )

Parameter
Parameter | Description
LoadingType | CRLoadingType (CRViewerLib). Indicates the type of data being loaded into the Report Viewer.


DrillOnDetail Event (CRViewer Object)

The DrillOnDetail event occurs when you drill down on a field in the Detail section of the report. This event is not available in the current version of the Report Viewer, but will be enabled in a future upgrade.

Syntax
Event DrillOnDetail ( FieldValues, SelectedFieldIndex As Long,

    UseDefault As Boolean )
Parameters

Parameter | Description
FieldValues | An array of objects containing details on the field.
SelectedFieldIndex | Long. The array index of the value in the field actually drilled on.
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


DrillOnGraph Event (CRViewer Object)

The DrillOnGraph event occurs when you drill down on a graph.

Syntax
Event DrillOnGraph ( PageNumber As Long, x As Long, y As Long,

    UseDefault As Boolean )
Parameters

Parameter | Description
PageNumber | Long. The page number of the report containing the graph where the event occurred.
x | Long. The X coordinate of the graph that was drilled on.
y | Long. The Y coordinate of the graph that was drilled on.
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


DrillOnGroup Event (CRViewer Object)

The DrillOnGroup event occurs when drilling down (double-clicking) on a group field viewer window.

Syntax
Event DrillOnGroup ( GroupNameList, DrillType As CRDrillType,

    UseDefault As Boolean )
Parameters

Parameter | Description
GroupNameList | An array containing all group names for the group drilled on.
DrillType | CRLoadingType (CRViewerLib). Specifies what type of object the drill event occurred on (for example, graph, group tree, map, etc.).
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


DrillOnSubreport Event (CRViewer Object)

The DrillOnSubreport event occurs when drilling down (double-clicking) on a subreport.

Syntax
Event DrillOnSubreport ( GroupNameList, SubreportName As String,

    Title As String, PageNumber As Long,

    Index As Long, UseDefault As Boolean )
Parameters

Parameter | Description
GroupNameList | An array containing all group names for the group drilled on.
SubreportName | String. Indicates the name of the subreport that was drilled on.
Title | String. Indicates the title of the subreport that was drilled on.
PageNumber | Long. Indicates the page number that the event occurred on.
Index | Long. Indicates the index of the subreport that was drilled on.
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


ExportButtonClicked Event (CRViewer Object)

The ExportButtonClicked event occurs when the Export button is clicked.

Syntax

Event ExportButtonClicked ( UseDefault As Boolean )

Parameter

Parameter | Description
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


FirstPageButtonClicked Event (CRViewer Object)

The FirstPageButtonClicked event occurs when the button which navigates through the report to the first page is clicked.

Syntax

Event FirstPageButtonClicked ( UseDefault As Boolean )

Parameter

Parameter | Description
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


GoToPageNClicked Event (CRViewer Object)

The GoToPageNClicked event occurs when a user requests and goes to a specific page in the report.

Syntax

Event GoToPageNClicked ( UseDefault As Boolean, PageNumber As Integer )

Parameters

Parameter | Description
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.
PageNumber | Integer. The page number of the page that is to be displayed.


GroupTreeButtonClicked Event (CRViewer Object)

The GroupTreeButtonClicked event occurs when the Group Tree button is clicked to show/hide the Group Tree in the viewer window.

Syntax

Event GroupTreeButtonClicked ( Visible As Boolean )

Parameter

Parameter | Description
Visible | Boolean. Indicates whether or not the Group Tree is now visible.


HelpButtonClicked Event (CRViewer Object)

The HelpButtonClicked event occurs when the Help button is clicked.

Syntax

Event HelpButtonClicked ()


LastPageButtonClicked Event (CRViewer Object)

The LastPageButtonClicked event occurs when the button which navigates through the report to the last page is clicked.

Syntax

Event LastPageButtonClicked ( UseDefault As Boolean )

Parameter

Parameter | Description
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


NextPageButtonClicked Event (CRViewer Object)

The NextPageButtonClicked event occurs when the button which navigates through the report to the next page is clicked.

Syntax

Event NextPageButtonClicked ( UseDefault As Boolean )

Parameter

Parameter | Description
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


OnReportSourceError Event (CRViewer Object)

The OnReportSourceError event occurs when the report source (assigned to the CRViewer.ReportSource property) causes an error or cannot be loaded by the Report Viewer.

Syntax
Event OnReportSourceError ( errorMsg As String,

    errorCode As Long, UseDefault As Boolean )
Parameters

Parameter | Description
errorMsg | String. Indicates the error message.
errorCode | Long. Indicates the code or ID for the error.
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


PrevPageButtonClicked Event (CRViewer Object)

The PrevPageButtonClicked event occurs when the button which navigates through the report to the previous page is clicked.

Syntax

Event PrevPageButtonClicked ( UseDefault As Boolean )

Parameter

Parameter | Description
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


PrintButtonClicked Event (CRViewer Object)

The PrintButtonClicked event occurs when the Print button is clicked.

Syntax

Event PrintButtonClicked ( UseDefault As Boolean )

Parameter

Parameter | Description
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


RefreshButtonClicked Event (CRViewer Object)

The RefreshButtonClicked event occurs when the Refresh button is clicked.

Syntax

Event RefreshButtonClicked ( UseDefault As Boolean )

Parameter

Parameter | Description
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


SearchButtonClicked Event (CRViewer Object)

The SearchButtonClicked event occurs when the Search button is clicked.

Syntax

Event SearchButtonClicked ( searchText As String, UseDefault As Boolean )

Parameters

Parameter | Description
searchText | String. Indicates the data being searched for.
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


SearchExpertButtonClicked Event (CRViewer Object)

The SearchExpertButtonClicked event occurs when the Search Expert button is clicked.

Syntax

Event SearchExpertButtonClicked ( UseDefault As Boolean )

Parameter

Parameter | Description
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


SelectionFormulaBuilt Event (CRViewer Object)

The SelectionFormulaBuilt event occurs when a new selection formula is assigned to the report. This event is not valid when the Report Viewer is used in conjunction with the Report Designer Component.

Syntax
Event SelectionFormulaBuilt (

    selctionFormula As String, UseDefault As Boolean )
Parameters

Parameter | Description
selectionFormula | String. Indicates the new selection formula assigned to the report.
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


SelectionFormulaButtonClicked Event (CRViewer Object)

The SelectionFormulaButtonClicked event occurs when the Selection Formula button in the Report Viewer is clicked. This is not valid when the Report Viewer is assigned a report source produced by the Report Designer Component.

Syntax
Event SelectionFormulaButtonClicked (

    selctionFormula As String, UseDefault As Boolean )
Parameters

Parameter | Description
selectionFormula | String. The current selection formula that will be replaced.
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


ShowGroup Event (CRViewer Object)

The ShowGroup event occurs when you click a group in the Group Tree.

Syntax

Event ShowGroup ( GroupNameList, UseDefault As Boolean )

Parameters

Parameter | Description
GroupNameList | An array containing all group names for the group selected.
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


StopButtonClicked Event (CRViewer Object)

The StopButtonClicked event occurs when the user clicks the Stop button in the Report Viewer, forcing the Viewer to stop loading data from the report source.

Syntax
Event StopButtonClicked (

    loadingType As CRLoadingType, UseDefault As Boolean )
Parameters

Parameter | Description
loadingType | CRLoadingType (CRViewerLib). Indicates what was being loaded into the Report Viewer when the Stop button was clicked.
UseDefault | Boolean. Indicates whether or not the default action of the event will be performed.


ViewChanged Event (CRViewer Object)

The ViewChanged event occurs after the view in the Report Viewer has changed. Views refer to the main Preview Tab and drill down tabs that appear in the Report Viewer as the user interacts with the report.

Syntax

Event ViewChanged ( oldViewIndex As Long, newViewIndex As Long )

Parameters

Parameter | Description
oldViewIndex | Long. An index referring to the view the user switched from.
newViewIndex | Long. An index referring to the view the user switched to.


ViewChanging Event (CRViewer Object)

The ViewChanging event occurs when there has been a request for the view in the Report Viewer to change. Views refer to the main Preview Tab and drill down tabs that appear in the Report Viewer as the user interacts with the report.

Syntax

Event ViewChanging ( oldViewIndex As Long, newViewIndex As Long )

Parameters

Parameter | Description
oldViewIndex | Long. An index referring to the view the user is switching from.
newViewIndex | Long. An index referring to the view the user is switching to.


ZoomLevelChanged Event (CRViewer Object)

The ZoomLevelChanging event occurs when the zoom level of the Report Viewer is changed.

Syntax

Event ZoomLevelChanged ( ZoomLevel As Integer )

Parameter

Parameter | Description
ZoomLevel | Integer. A value indicating the new zoom level percentage.


CRVTrackCursorInfo Object (CRVIEWERLib)

The CRVTrackCursorInfo Object contains information about the types of mouse cursors displayed while the user interacts with the report in the Report Viewer. This object corresponds to the TrackCursorInfo property in the CRViewer Object (CRVIEWERLib).

CRVTrackCursorInfo Object Properties

Property | Description | Read/Write
DetailAreaCursor | CRTrackCursor (CRViewerLib). Gets or sets the DetailAreaCursor type. | Read/Write
DetailAreaField Cursor | CRTrackCursor (CRViewerLib). Gets or sets the DetailAreaFieldCursor type. | Read/Write
GraphCursor | CRTrackCursor (CRViewerLib). Gets or sets the GraphCursor type. | Read/Write
GroupAreaCursor | CRTrackCursor (CRViewerLib). Gets or sets the GroupAreaCursor type. | Read/Write
GroupAreaField Cursor | CRTrackCursor (CRViewerLib). Gets or sets the GroupAreaFieldCursor type. | Read/Write


WebReportBroker Object (CRWEBREPORTBROKERLib)

The WebReportBroker Object is used internally by the Report Viewer to access web servers. In most applications, developers will not need to access this object directly.


WebReportSource Object (CRWEBREPORTBROKERLib)

The WebReportSource Object contains information and methods related to the display of a report by the Report Viewer.

WebReportSource Object Properties

Property | Description | Read/Write
ImageType | Reserved. Do not use in current development. Gets or sets the image type. | Read/Write
PromptOnRefresh | Boolean. Gets or sets the prompt mode. If TRUE, the user will be prompted for new information each time the Report Viewer displays the report. If FALSE, the user will not get a prompt and the information provided with the previous prompt will be used, unless the server requires new information. | Read/Write
ReportSource | Unknown. Gets or sets the report source for the WebReportBroker. | Read/Write
Title | String. Gets or sets the report title that can be displayed in viewer. | Read/Write
URL | String. Gets or sets the URL source for the report. | Read/Write


WebReportSource Object Methods

The following methods are discussed in this section:

AddParameter Method (WebReportSource Object)

AddParameterEx Method (WebReportSource Object)


AddParameter Method (WebReportSource Object)

Use AddParameter method to pass additional information for setting values for prompts in code as an alternative to prompting user to provide it. For example, you can provide user information which the server might request, rather than prompting the user to enter the information at runtime.

Syntax

Sub AddParameter ( tag As String, value As String )

Parameters

Parameter | Description
tag | String. Specifies the prompt for which you want to pass a value.
value | String. Specifies the response string that you want to provide.


AddParameterEx Method (WebReportSource Object)

AddParameterEx method is not implemented for the current release. This method will allow you to pass more information than AddParameter Method, which should be used at this time.


Enumerated Types - Report Viewer

The following enumerated types of the Report Viewer Object Model are discussed in this section:

CRLoadingType (CRViewerLib)

CRFieldType (CRViewerLib)

CRLoadingType (CRViewerLib)

CRObjectType (CRViewerLib)

CRTrackCursor (CRViewerLib)


CRDrillType (CRViewerLib)

Constant | Value
crDrillOnGraph | 2
crDrillOnGroup | 0
crDrillOnGroupTree | 1
crDrillOnMap | 3
crDrillOnSubreport | 4


CRFieldType (CRViewerLib)

Constant | Value
crBoolean | 5
crCurrency | 4
crDate | 6
crDateTime | 8
crInt16 | 1
crInt32 | 2
crInt8 | 0
crNumber | 3
crString | 9
crTime | 7
crUnknownFieldType | 255


CRLoadingType (CRViewerLib)

Constant | Value
LoadingNothing | 0
LoadingPages | 1
LoadingQueryInfo | 3
LoadingTotaller | 2


CRObjectType (CRViewerLib)

Constant | Value
crBitmap | 103 (&H67)
crBlob | 104 (&H68)
crBox | 106 (&H6A)
crCrossTab | 110 (&H6E)
crCrosstabChart | 108 (&H6C)
crCrosstabMap | 115 (&H73)
crDatabaseFieldType | 1
crDetailChart | 109 (&H6D)
crDetailMap | 116 (&H74)
crDetailSection | 202 (&HCA)
crFormulaFieldType | 5
crGraphic | 111 (&H6F)
crGroupChart | 107 (&H6B)
crGroupFooterSection | 201 (&HC9)
crGroupHeaderSection | 200 (&HC8)
crGroupMap | 114 (&H72)
crGroupNameFieldType | 8
crLine | 105 (&H69)
crOLAPChart | 113 (&H71)
crOLAPCrossTabFieldType | 4
crOLAPDataFieldType | 3
crOLAPDimensionFieldType | 2
crOLAPMap | 117 (&H75)
crOLEObject | 101 (&H65)
crOOPSubreport | 112 (&H70)
crPageFooterSection | 206 (&HCE)
crPageHeaderSection | 205 (&HCD)
crPromptingVarFieldType | 9
crReportFooterSection | 204 (&HCC)
crReportHeaderSection | 203 (&HCB)
crSpecialVarFieldType | 7
crSubreport | 102 (&H66)
crSummaryFieldType | 6
crText | 100 (&H64)
crUnknownFieldDefType | 0


CRTrackCursor (CRViewerLib)

Constant | Value
crAppStartingCursor | 12
crArrowCursor | 1
crCrossCursor | 2
crDefaultCursor | 0
crHelpCursor | 13
crIBeamCursor | 3
crMagnifyCursor | 99
crNoCursor | 10
crWaitCursor | 11


The Report Viewer/Java Bean Technical Reference

The following Properties, Methods, and Events are discussed in this section:

  • The Report Viewer/Java Bean Properties
  • The Report Viewer/Java Bean Methods
  • closeCurrentView
  • exportView
  • printView
  • refreshReport
  • searchForText
  • showLastPage
  • showPage
  • stopAllCommands
  • The Report Viewer/Java Bean Events
  • ServerRequestEvent
  • ViewChangeEvent


The Report Viewer/Java Bean Properties

The Report Viewer Bean properties may have one or more of the characteristics listed below:

  • read: you can get the current value.
  • write: you can set the value.
  • bound: you can get a notification every time the value changes.
  • constrained: you can veto a request to change the value.

    Property Description Read(r), Write(w),
    Bound(b), Constrained(c)

    busy

    Boolean. True if the ReportViewer is currently processing a command initiated by user action, method call, or property change.

    r, b

    canCloseCurrentView

    Boolean. True if the current views tab can be closed. The initial ("Preview") tab cannot be closed. Refer to method closeCurrentView.

    r,b

    canDrillDown

    Boolean. True if drill-down views can be opened. Normally, clicking on a hidden group in the group tree (indicated by a magnifying glass icon next to the group name) or double-clicking on a chart or map or group section in the page will open a drill-down view.

    r,w,b,c

    currentMessage

    string. The message currently displayed in the status area of the toolbar.

    r,b

    currentPageNumber

    int. The number of the page currently being viewed.

    r,b

    currentTip

    string. The "tool tip" currently displayed in the status area of the toolbar. Tool tips temporarily override any message in the status area.

    r,b

    currentViewName

    string. The name of the view whose tab is selected.

    r,b

    exportingPossible

    Boolean. False if exporting is not possible because the user has denied the bean permission to write to the local disk.

    r

    hasExportButton

    Boolean. True if the Export button can be made visible in the toolbar. If exporting is not possible (refer to property exportingPossible ), requests to set this property to True will be vetoed.

    r,w,b,c

    hasGroupTree

    Boolean. If set to True then the GroupTree toggle button is made visible in the toolbar and the GroupTree can be displayed (refer to property showGroupTree).

    r,w,b,c

    hasPrintButton

    Boolean. If True then the Print button will be visible in the toolbar. If printing is not possible (refer to property printingPossible) then requests to set this property to True will be vetoed.

    r,w,b,c

    hasRefreshButton

    Boolean. If True then the Refresh button is visible in the toolbar.

    r,w,b,c

    hasToolBar

    Boolean. If True then the toolbar is visible.

    r,w,b,c

    hasTextSearch
    Controls

    Boolean. If True then the Text Search field and the Find Next button are visible in the toolbar.

    r,w,b,c

    language

    string. Contains the 2 letter international Standard code for the language to be used for the user interface. Languages currently supported are:

    English -- en

    French -- fr

    German -- de

    Japanese -- ja

    Italian -- it

    Spanish -- es

    Portuguese -- pt

    r,w,b,c

    lastPageNumber

    int. Indicates to the highest numbered page currently available in the report. This may or may not be the final page. (refer to property lastPageNumberKnown).

    r,b

    lastPageNumber
    Known

    Boolean. True if the number of the final page in the report is known. If False then there are more pages in the report than the lastPageNumber property indicates.

    r,b

    printingPossible

    Boolean. True if printing is possible. If False then either the Java implementation doesn't support it or the user has denied the bean permission to print.

    r

    reportName

    string. The URL of the report to be viewed. For example:
    http://server_name/report_dir/report.rpt
    Setting this property causes the ReportViewer to request page 1 of the report from the server.

    r,w,b,c

    searchText

    string. Contains the text most recently searched for, or the text being typed by the user int to the Text Search field in the toolbar.

    r,b

    selectionFormula

    string. The current selection formula to be used for subsequent commands. The formula is expressed in the Crystal Reports formula language. Setting this property closes all views except the initial one (the "Preview" view), discards all information cached for the report, and re-requests the current page of the report.

    r,w,b,c

    showGroupTree

    Boolean. If True and the hasGroupTree property is True then the GroupTree will be visible.

    r,w,b,c


The Report Viewer/Java Bean Methods

Each of the methods in the Report Viewer Bean starts what may be a lengthy operation, and they return to the caller before that operation is complete. If it is important to know when the command begun by one of these methods is finished, the calling code should watch for the associated events or property change notifications.

Generally there will be a time delay between the method call returning and the associated event being fired or the property changing. In fact, there may be a delay in beginning the command if the report viewer is busy processing a previous command. Commands are begun strictly one at a time in the order they are generated although, once begun, they may be processed in parallel in different threads.

The events and property change notifications will be given to the calling code on a different thread from the one that made the method call.

closeCurrentView

exportView

printView

refreshReport

searchForText

showLastPage

showPage

stopAllCommands


closeCurrentView

If the canCloseCurrentView property is True, closes the current view. Equivalent to the Close button in the toolbar. A viewClosed and a viewActivated event are fired. The currentViewName property is changed.

Syntax

void closeCurrentView ()


exportView

If the exportingPossible property is True, requests the report from the server in the indicated format and writes it to the local disk. Similar to the Export button in the toolbar.

Syntax

void exportView ( int exportFormat, File destinationFile )

Parameters

exportFormat

Specifies the format in which the requested report should appear.

Constant | Value
toHTML | 0
toCrystalReport | 1
toMSWord | 2
toMSExcel | 3

destinationFile

Complete pathname of the destination file.


printView

If the printingPossible property is True, prints all pages in the current view, requesting them from the server if necessary. Equivalent to the Print button in the toolbar.

Syntax

void printView ()


refreshReport

Closes all views except the initial one (the "Preview" view), discards all information cached for the report, and re-requests the current page of the report.

Syntax

void refreshReport ()


searchForText

Displays the next occurrence of the indicated text in the report output. Equivalent to the text search field in the toolbar. Currently, the second and third parameters are ignored; the search is always forward and case-insensitive. The searchText property is changed.

Syntax
void searchForText ( String searchString, boolean forwardSearch,

    boolean caseSensitive )
Parameters

searchString | The string for which you want to search.
forwardSearch | This parameter is ignored.
caseSensitive | This parameter is ignored.


showLastPage

Shows the last page of the report, requesting it from the server if necessary. Equivalent to the Last Page button in the toolbar. The lastPageNumber and lastPageNumberKnown properties may be changed.

Syntax

void showLastPage ()


showPage

Displays the indicated page, requesting it from the server if necessary. Equivalent to the page number field in the toolbar. The currentPageNumber property is changed.

Syntax

void showPage ( int pageNumber )

Parameter

pageNumber

Number of the page to be displayed.


stopAllCommands

Cancels all unfinished commands. Equivalent to the Stop button in the toolbar.

Syntax

void stopAllCommands ()


The Report Viewer/Java Bean Events

There are 2 event classes defined by the Report Viewer Bean and discussed in this section: class ViewChangeEvent and class ServerRequestEvent.


ServerRequestEvent

Description | Properties | ListenerInterface Methods
Indicates a request has been sent to the server owning the current report. | string ServerURL string Parameter | requestStarted(event e) requestEnde(event e)


ViewChangeEvent

Description | Properties | ListenerInterface Methods
Indicates that a view has changed. | string viewName | viewOpened(event e) viewActivated(event e) viewClosed(event e)


Embeddable Crystal Reports Designer Control Object Model

The Embeddable Crystal Reports Designer Control (Embeddable Designer) is a new addition to the Report Designer Component; it enables you to provide a Crystal Reports designer in your application. In this section, you will find a general overview of the control as well as detailed information on its properties and methods.

Click the appropriate link to jump to that section:

  • Overview of the Embeddable Designer
  • Application development with the Embeddable Designer
  • Distributing the Embeddable Designer
  • Properties and methods of the Embeddable Designer


Overview of the Embeddable Designer

Your users can now design or edit reports at runtime with the Embeddable Designer. This easy-to-use ActiveX control provides the full power of Crystal Reports to your application. The control is placed on a form, or in a container within the form, and displays a new or existing report in design mode. This presents the user with an interactive environment in which to design or edit the report. The Embeddable Designer allows users to:

  • add data sources
  • add database fields
  • create and add formulas
  • create and add parameters
  • group data
  • summarize data
  • add charts
  • add subreports
  • add special fields
  • format fields and sections.


Application development with the Embeddable Designer

The Embeddable Designer is an ActiveX control that can be added to any development environment that supports ActiveX. Using Microsoft Visual Basic, Microsoft Visual C++, Delphi, and Borland C++, you can now add a Crystal Reports designer to your application with minimal code.

As a standard component, the Embeddable Designer not only exposes several properties at design time, but also provides a complete set of properties, methods, and events that can be programmed at runtime. An application using the Embeddable Designer will consist of three components. These three components allow the user to create, design, preview, print, export, and save their reports.

  • The Embeddable Designer, also known as the Embeddable Crystal Reports 8.5 Designer Control (Crdesignerctrl.dll), is a front-end user interface for designing or editing new or existing reports. See Programming the Embeddable Crystal Reports Designer Control for tutorials on creating applicaions with the Embeddable Designer.
  • The Automation Server, also known as the Crystal Reports 8.5 ActiveX Designer Design and Runtime Library (Craxddrt.dll), is an extensive object model with hundreds of properties and methods that you can use to program a report. See Report Designer Component Object Model for more information.

    Note: The Craxddrt.dll must only be used in a client-side application. See Unification of the RDC object model for more information.

  • The Report Viewer, also known as the Crystal Reports Viewer Control (Crviewer.dll), is a front-end user interface for viewing reports. See Programming the Crystal Report Viewers for more information.


Distributing the Embeddable Designer

Distribution of an application consists of three main DLLs: Crdesignerctrl.dll, Craxddrt.dll, and Crviewer.dll. In addition to these main DLLs, you will need to distribute the standard runtime files, including database DLLs and export DLLs. The additional DLLs you distribute will vary depending on your application. For more information on standard runtime files, refer to the Crystal Reports Developer Runtime Help (Runtime.hlp).

Note: The Embeddable Designer is not royalty free; it requires licensing. For more information on licensing, refer to the License Manager Help (License.hlp).

Providing online help for the Embeddable Designer

Although online help for designing reports at runtime in the Embeddable Designer is not provided, you can provide your own online help to your users. The Embeddable Designer has access to online help through the Help button on the main toolbar and through the Help command in the shortcut menu. You can enable or disable the Help button and hide the Help menu through the EnableHelp property (Microsoft Visual Basic) or the SetEnableHelp function (Microsoft Visual C++). To set your help file to the Embeddable Designer, create the following registry key:

Key Name

HKEY_LOCAL_MACHINE\SOFTWARE\Seagate Software\Report Designer Component

Value Name

CrdesignerctlHelpPath

Value Data

Provide the full path and name of your help file here.

The Embeddable Designer uses the WinHelp function to start Microsoft Windows Help. The following table lists the various help options available and the UCommand used in the WinHelp function based on the help option selected. Keep this in mind when creating your online help.

Note: The online help must be a WinHelp file (.hlp).

Option Location | UCommand
Menu: Help > Crystal Reports Help | HELP_INDEX
Menu: Help > Search | HELP_FINDER
Menu: Help > Using Help | HELP_HELPONHELP
Toolbar: Help | HELP_INDEX

For a complete description of the WinHelp function see "WinHelp Shell and Common Controls: Platform SDK" in the Microsoft Developer Network (MSDN).


Properties and methods of the Embeddable Designer

In Microsoft Visual Basic, the properties of the Embeddable Designer are Read/Write. In Microsoft Visual C++, the corresponding functions will have Set and Get prefixed to the property name. Set writes to the property, and Get reads from the property. Methods and events have the same names in both environments.

Note: Only the properties and methods of the CCRDesignerCtrl class (main class for the Embeddable Designer) are included. Information on properties, methods, and events for the base classes can be found in the Microsoft Developer Network (MSDN).

Microsoft Visual Basic Example

Dim bShowGrid As Boolean

' Get the value of the DisplayGrid property
bShowGrid = CRDesignerCtrl1.DisplayGrid

' If the Grid is displayed Set the DisplayGrid
' property to False
If bShowGrid Then CRDesignerCtrl1.DisplayGrid = False

Microsoft Visual C++ Example

BOOL bShowGrid;

// Get the value for the DispalyGrid property
bShowGrid = m_Designer.GetDisplayGrid();

// If the Grid is displayed Set the DisplayGrid
// property to False
if(bShowGrid) m_Designer.SetDisplayGrid(FALSE);


Embeddable Designer (Properties)

Property | Data type and description | Read/Write
CaseInsensitiveSQLData | Boolean. Specifies whether or not to perform a case insensitive search for SQL data. | Read/Write
ConvertDateTimeType | CRConvertDateTimeType. Gets or sets the report option that specifies the format to be converted for date / time fields. | Read/Write
ConvertNullFieldToDefault | Boolean. Specifies whether or not to convert NULL parameter fields to their default values. | Read/Write
DisplayFieldView | Boolean. Gets or sets whether or not the field view is available. The field view is the list of available fields for the report, including Database, Formula, Parameter, Group Name, Running Total, Special, and Unbound fields. | Read/Write
DisplayGrid | Boolean. Gets or sets whether or not the grid is displayed. | Read/Write
DisplayHiddenSections | Boolean. Gets or sets whether or not a section is available when hidden. | Read/Write
DisplayRulers | Boolean. Gets or sets whether or not the Ruler is available. | Read/Write
DisplayToolbar | Boolean. Gets or sets the visibility of the tool-bar. | Read/Write
EnableHelp | Boolean. Gets or sets the availability of the help options. When True, the Help icon on the toolbar is enabled and the Help command is visible in the shortcut menu. When False, the Help Icon on the toolbar is disabled and the Help command is hidden in the shortcut menu. | Read/Write
EnableSnapToGrid | Boolean. Specifies whether or not to automatically align any fields you insert or to resize to the nearest grid coordinate. | Read/Write
GridSize | Single. Gets or sets the size of the grid in inches. Default value is 0.083. | Read/Write
ReportObject | ReportObject. Gets or sets the report object. | Read/Write
TranslateDosMemos | Boolean. Gets or sets the report option that indicates whether or not to translate DOS memos. | Read/Write
TranslateDosStrings | Boolean. Gets or sets the report option that indicates whether or not to translate DOS strings. | Read/Write
UseIndexForSpeed | Boolean. Gets or sets the "Use Indexes or Server for Speed" option during record selection report option. | Read/Write
VerifyOnEveryPrint | Boolean. Gets or sets the report option that indicates whether or not to verify the database every time the report is run. | Read/Write


Embeddable Designer (Methods)

SaveReport Method

Use the SaveReport method to the save the report to Crystal Reports format.

Syntax
Sub SaveReport (ReportName as String)
Parameter

Parameter | Description
ReportName | Specifies the file path and name that you want to save the report to.


Visual Basic Solutions

Crystal Reports offers you a wide range of solutions for your reporting needs. This section provides a general overview of the more common Crystal Reports development tools. These include the Crystal Report Engine API, Crystal ActiveX Control, and Crystal Report Engine Automation Server, but not the Report Designer Component. The Report Designer Component is the preferred Development tool and is described in previous sections.

Click the appropriate link to jump to that section:

  • Enhancements to the Crystal Report Print Engine API
  • Crystal ActiveX Controls
  • Crystal Report Engine Automation Server
  • Grid Controls and the Crystal Report Engine
  • Grid Controls and the Crystal Report Engine


Enhancements to the Crystal Report Print Engine API

There are many enhancements to the API that correspond to enhancements in Version 8 and 8.5 of Crystal Reports. For a more detailed description of the enhancements that follow, refer to the documentation for the related functionality in the Crystal Reports User's Guide. For developer reference information on each of the new and enhanced calls, see the Crystal Reports Developer's Help (CrystalDevHelp.chm) or the Crystal Reports Technical Reference Guide.

Many new API structures and functions have been introduced and many existing ones have been enhanced, as outlined in the following sections:

  • Version 8.5 enhancements
  • Version 8 enhancements


Version 8.5 enhancements

The following enhancements apply to version 8.5 of Crystal Reports.

Click the appropriate link to jump to that section:

  • Create, modify, and monitor Report Alerts
  • Get report version information
  • New additions to the PEReportOptions structure
  • Additional error codes


Create, modify, and monitor Report Alerts

Report Alerts are custom messages created in the Crystal Reports Designer that appear when certain conditions are met by data in a report. Report Alerts may indicate action to be taken by the user or information about report data. For more information see Report Alerts in the Crystal Reports User Guide.

Two new structures and seven new functions have been added to the Crystal Report Engine API to allow you to create, modify, and monitor Report Alerts at runtime. These structures and their functions are:

  • PEAlertInstanceInfo
  • PEGetNthAlertInstanceInfo
  • PEReportAlertInfo
  • PEGetNReportAlerts
  • PEEnableNthAlert
  • PEGetNthReportAlert
  • PESetNthAlertConditionFormula
  • PESetNthAlertDefaultMessage
  • PESetNthAlertMessageFormula


Get report version information

In the CRPE API you may now get the report's version information. A new structure, PEVersionInfo, has been added to hold the major number, minor number, and letter information. The structure is returned by calling the newly added function, PEGetReportVersion.


New additions to the PEReportOptions structure

In the CRPE API, three new elements are now supported in the structure, PEReportOptions:

  • alwaysSortLocally
  • isReadonly
  • canSelectDistinctRecords

You may use the CRPE API calls, PEGetReportOptions and PESetReportOptions, to obtain or set report options.


Additional error codes

The CRPE API now supports three new error codes. These error codes are:

  • PE_ERR_READONLYPARAMETEROPTION
  • PE_ERR_MINGREATERTHANMAX
  • PE_ERR_INVALIDSTARTPAGE

For more information see Error Codes.


Version 8 enhancements

The following enhancements apply to version 8 of Crystal Reports.

Click the appropriate link to jump to that section:

  • Launch Seagate Analysis.
  • Basic and Crystal Syntax support.
  • Charting enhancements.
  • Hierarchical grouping.
  • Hyperlinks & On-demand subreports.


Launch Seagate Analysis

You may now have users click a button on the preview window toolbar to launch Seagate Analysis and open the current report.

A new event, LaunchSeagateAnalysisEvent, has been added. If you enable the event, and the user clicks the Launch Seagate Analysis button, the LaunchSeagateAnalysisEvent will be fired. The user will be prompted to save the file and Seagate Analysis will be launched with the current report open.

There are a number of other enhancements in the CRPE API that complement those in corresponding components of the Crystal Report Designer.


Basic and Crystal Syntax support

Since the Crystal Reports formula language has been enhanced to support a Basic-like syntax as well as the Crystal syntax, existing Formula API calls have been modified accordingly.

In all the Formula calls now, SET uses the syntax specified by the user and GET sets a flag that the user can later retrieve.

Two new API calls, PESetFormulaSyntax and PEGetFormulaSyntax, have also been added.


Charting enhancements

The following are several enhancements for charting:

  • Automatic scaling for axes
  • Default titles
  • Legend layout
  • Fractional point size
Automatic scaling for axes

In the CRPE API, three new elements are now supported in the structure, PEGraphAxisInfo:

  • dataAxisYAutoScale
  • dataAxisY2AutoScale
  • seriesAxisAutoScale

You may use the CRPE API calls, PEGetGraphAxisInfo and PESetGraphAxisInfo, to obtain or set automatic scaling for the graph axes.

Default titles

The Crystal Report Designer, by default, now creates title, subtitle, footnote, X-axis title, Y-axis title and Z-axis title. In the CRPE API, you can use PEGetGraphTextDefaultOption and PESetGraphTextDefaultOption to manipulate these items. To use these calls, you will need to specify a PE_GTT_* constant that corresponds to each of the titles, and set useDefault as TRUE or FALSE.

Legend layout

In the CRPE API, you may now set the legendLayout element in PEGraphOptionInfo structure to one of the PE_GLL_* constants. You may also use the CRPE API calls, PEGetGraphOptionInfo and PESetGraphOptionInfo, to get or set legend layout options.

Fractional point size

For fonts, there is now support for fractional point sizes including the 10.5 point font size commonly used in Japanese. A new twipSize element has been added to the structure PEFontColorInfo. Related functions and methods now return or apply the twipSize element if the pointSize element is zero. The functions affected are:

  • PEGetGraphFontInfo
  • PESetGraphFontInfo


Hierarchical grouping

In the Crystal Report Designer, you may now use hierarchical grouping to arrange data in a report to show hierarchical relationships in your data.

To support hierarchical grouping, the PEGroupOptions structure and the PEGetGroupOptions and PESetGroupOptions calls in the CRPE API have been modified.


Hyperlinks & On-demand subreports

The CRPE API has been enhanced to support hyperlinks and on-demand subreports.

New elements have been added to the PETrackCursorInfo structure to support these enhancements:

  • short ondemandSubreportCursor - this cursor can be set to display over on-demand subreports when drilldown for the window is enabled; the default is PE_TC_MAGNIFY_CURSOR.
  • short hyperlinkCursor - this cursor can be set to display over any report object that contains hyperlink text; the default is PE_TC_HAND_CURSOR.
  • new cursor types:
      • PE_TC_BACKGROUND_PROCESS_CURSOR
      • PE_TC_GRAB_HAND_CURSOR
      • PE_TC_ZOOM_IN_CURSOR
      • PE_TC_REPORT_SECTION_CURSOR
      • PE_TC_HAND_CURSOR


Using the Crystal Report Engine API in Visual Basic

This section provides additional information for developers working in Visual Basic. Several features of the Crystal Report Engine must be handled differently in Visual Basic than in other development environments. In addition, some of the topics here are designed to simply assist Visual Basic programmers in the design of applications using the Crystal Report Engine.

The following topics are discussed in this section:

  • When to Open/Close the Crystal Report Engine.
  • Embedded Quotes in Visual Basic Calls to the Crystal Report Engine.
  • Passing Dates/Date Ranges in Visual Basic using the Crystal Report Engine API Calls.
  • Identifying String Issues in Visual Basic Links to the Crystal Report Engine.
  • Hard-coded Nulls in Visual Basic User Defined Types.
  • Visual Basic Wrapper DLL.
  • CRPE32.DEP.


When to Open/Close the Crystal Report Engine

In a Visual Basic application, you can either open the Crystal Report Engine when you open your application or when you open a form. As a general rule, it is always best to open the Crystal Report Engine when you open the application and close it when you close the application. Here is why:

  • When you open and close a form, the Crystal Report Engine opens every time you open the form and closes every time you close the form. If you print a report, close the form, and later decide to print a report again, the application has to reopen the Crystal Report Engine when you open the form, creating a time delay while running your application.
  • When you open and close the application, the Crystal Report Engine opens as you start the application, and stays open as long as the application is open. Once the Crystal Report Engine is open, you can print a report as often as you wish without the need to reopen the Crystal Report Engine every time you print.


Embedded Quotes in Visual Basic Calls to the Crystal Report Engine

When you pass a concatenated string from Visual Basic to the Crystal Report Engine (for example, for a record selection formula), it is important that the resulting string has the exact syntax that the Crystal Report Engine expects. You should pay special attention to embedded quotes in concatenated strings because they are often the source of syntax errors.

Several examples follow. The first example shows code with a common embedded quote syntax error and the last two examples show code using the correct syntax.

Incorrect syntax

VBNameVariable$ = "John"
Recselct$ = "{file.LASTNAME} = " + VBNameVariable$

This code results in the string:

{file.LASTNAME} = John

Since John is a literal string, the Formula Checker expects to see it enclosed in quotes. Without the quotes, the syntax is incorrect.

Correct syntax

VBNameVariable$ = "John"

Recselct$ = "{file.LASTNAME} = " +

(chr$(39) + VBNameVariable + chr$(39)

This code results in the string:

{file.LASTNAME} = 'John'

This is the correct syntax for use in a Crystal Reports record selection formula. This is the syntax you would use if you were entering a selection formula directly into Crystal Reports.

VBNameVariable$ = "John"

Recselct$ = "{file.Lastname} = "

(+ "'" + VBNameVariable + "'"

This code also results in the string:

{file.LASTNAME} = 'John'

Again, the correct syntax.


Passing Dates/Date Ranges in Visual Basic using the Crystal Report Engine API Calls

You may want to pass date or date range information from your Visual Basic application to the Crystal Report Engine for use in formulas, selection formulas, etc. Here is an example showing a way to do it successfully:

  1. Start by opening a print job and assigning the print job handle to a variable.
JobHandle% = PEOpenPrintJob ("C:\CRW\CUSTOMER.RPT")
  2. Create variables that hold the year, month, and day for both the start and end of the range.
StartYear$ = 1992

StartMonth$ = 01

StartDay$ = 01

EndYear$ = 1993

EndMonth$ = 12

EndDay$ = 31
  3. Now build a string to pass to the record selection formula. This is done in two steps:
  • First, build the starting and ending dates for the date range.
      • Assign the starting date string to the variable StrtSelect$.
      • Assign the ending date string to the variable EndSelect$.
StrtSelect$ = "{filea.STARTDATE} < Date

(" + StartYear$ + ", " + StartMonth$ + ", "

+ StartDay$ +")"
EndSelect$ = "{filea.ENDDATE} < Date

(" + EndYear$ + ", " + EndMonth$ +

", " + EndDay$ +")"
  • Second, build the selection formula using the StrtSelect$ and EndSelect$ variables.

Recselct$ = StrtSelect$ + " AND " + EndSelect$

  4. Once your formula is built, set the record selection formula for the report.
RetCode% = PESetSelectionFormula

(JobHandle%, RecSelect$)
  5. Finally, print the report.
RetCode% = PEStartPrintJob (JobHandle, 1)

RetCode% = PEClosePrintJob (JobHandle, 1)
  6. Modify this code to fit your needs.


Identifying String Issues in Visual Basic Links to the Crystal Report Engine

When passing a string to the Crystal Report Engine as part of the Custom-Print Link, you may think that you are passing one thing when the program, in fact, is passing something entirely different. This can happen easily, for example, when you are passing a concatenated string that you have built using variables. A small syntax error (with embedded quotes, for example) can lead to an error message and a failed call. A simple debugging procedure follows.

To Identify a String Issue (bug)

To identify a string bug, have the program display what it is passing in a message box. To do so, put a line of code similar to the following immediately after the call in question:

MsgBox (variablename)

Look at the string that is displayed and make certain that it is exactly what Crystal Reports expects for a string.

  • If the syntax is incorrect, look for errors in the concatenated string you have built.
  • If the syntax is correct, look for other problems that could have caused the call to fail.
  • If you are not sure if the syntax is correct, write down the string from the message box, enter it in the Crystal Reports Formula Editor, and click the Check button. If there is an error in the string, the Formula Checker will identify it for you.


Hard-coded Nulls in Visual Basic User Defined Types

When you assign a string to a user defined type in Visual Basic, it is necessary to hard-code a null immediately after the string. For example:

myStruct.stringField = "Hello" + CHR$(0)


Visual Basic Wrapper DLL

Some of the features of the Crystal Report Engine API are not directly available to Visual Basic programmers, due to restrictions in the Visual Basic language, while others present technological issues that are better handled differently from what was originally designed in the Report Engine API. To avoid problems calling functions in the API, you may want to consider using the Crystal ActiveX Controls, or the Crystal Report Engine Automation Server. However, if you prefer to work with the API, Crystal Reports includes the Visual Basic Wrapper DLL, CRWRAP32.DLL.

The Visual Basic Wrapper DLL has been designed specifically for programming in the Visual Basic environment and can be used to build Crystal Report Engine applications in Visual Basic 4.0 or later. The CRWRAP.BAS module, installed by default in the \Seagate Software\Crystal Reports directory, redefines many of the functions and structures defined in GLOBAL.BAS. When working with the Crystal Report Engine API, add both modules to your Visual Basic project.

The functions and structures defined in the Visual Basic Wrapper DLL provide an interface for handling export formats, parameter fields, SQL server and ODBC logon information, graphs, printing, and more. For complete information on each of the structures and functions included, search for Visual Basic Wrapper for the Crystal Report Engine. In most cases, each function or structure has a corresponding function or structure in the original Crystal Report Engine API with a similar name. When working in Visual Basic though, you must use the functions and structures provided by the Visual Basic Wrapper DLL.


CRPE32.DEP

The crpe32.dep dependency file contains only the most often used runtime files for Visual Basic. The file can be modified to include any runtime file. To include a file that is not being distributed when using the existing crpe32.dep, you may add the new file to the "Additional Runtime DLLs" section. However, you must continue a sequential order to the Uses=.

For example:

If you want to include the p2BACT.DLL, you must add it under the "Additional Runtime DLLs" section of crpe32.dep.

If the last numbered Uses= is:

Uses46=\program files\seagate software\sschart\SSCSDK32.DLL

To include the p2BACT.DLL, add the following line to crpe32.dep:

Uses47=..\crystal\p2BACT.DLL


Crystal ActiveX Controls

ActiveX Controls Properties

ActiveX Controls Methods

ActiveX Controls Error Messages

ActiveX controls bring more powerful applications to desktops and networks. ActiveX moves beyond applications that produce static documents to a Windows environment that provides active controls, documents, and client applications that can operate and interact not only with each other, but also with network intranets and the global Internet.

ActiveX controls provide plug-in capabilities that let you add application components, and even entire applications, to your own development projects without writing a line of code. Crystal Reports includes the Crystal ActiveX Control. Use the ActiveX Control to easily add all of the report processing power of Crystal Reports to your own Visual Basic, Visual C++, Borland C++, Delphi, and other applications.

Note:

  • The development tools may refer to an ActiveX Control by any of the following names: OLE Control, OCX Control, Custom Control, or ActiveX Control. As long as the term used refers to a control with an .OCX filename extension, it is synonymous with the term ActiveX Control used here.

The following topics are discussed in this section:

Adding the ActiveX Control to your Project

Using the ActiveX Controls

Crystal Report Engine Automation Server


Adding the ActiveX Control to your Project

This section demonstrates how to add the Crystal ActiveX Control to an application project being designed in Visual Basic versions 5.0 and 6.0. If you wish to use the ActiveX Control in a different development environment or a different version of Visual Basic, please refer to the documentation that came with your development tools for information on adding an ActiveX or OLE Control (OCX) to your project.

The Crystal ActiveX Control was installed in the \WINDOWS\SYSTEM directory when you installed Crystal Reports. You add the ActiveX Control to your Visual Basic project using the Components command on the Visual Basic Project menu.

  1. Open Visual Basic.
  2. Open the project to which you want to add the ActiveX Control.
  3. Choose Components from the Project menu.

    The Components dialog box appears.

  • If Crystal Report Control appears in the Available Controls list, click the check box next to it, click OK, and skip to Step 6.
  • If Crystal Report Control does not appear in the Available Controls list, click Browse. The Add ActiveX Control dialog box appears.

Note: Crystal Report Control is the name of the Crystal ActiveX Control when it is added to a development project. The term ActiveX Control refers to a type of control, while Crystal Report Control is the name of the ActiveX Control provided by Crystal Reports.

  4. Use the controls in the Add ActiveX Control dialog box to locate and select the CRYSTL32.OCX file. This file was installed in your \WINDOWS\SYSTEM directory when you installed Crystal Reports. Once you locate and select the file, click Open.
  5. Crystal Report Control will now appear in the Available Controls list box. Click the check box next to the name of the control, and click OK.

    Visual Basic adds the Crystal ActiveX Control to your toolbox. The tool looks like this:

    {bml ocx_cntl.bmp}

  6. To add the ActiveX Control to a form, double-click the tool in the toolbox and Visual Basic installs it on the active form.

Note: For instructions on how to add an ActiveX Control or OLE control to development applications other than Visual Basic, refer to the documentation that came with the development application you are using.


Using the ActiveX Controls

Once you have the ActiveX Control object on your form, you build the connection between your application and Crystal Reports by setting the object's properties at design time or changing properties at runtime. The ActiveX properties let you specify:

  • the name of the report you want to print in response to an application event.
  • the destination for that report (window, file, or printer).
  • the number of copies you want to print (if your report is going to the printer).
  • print file information (if your report is going to a file).
  • preview window sizing and positioning information (if your report is going to a window).
  • selection formula information (if you want to limit the records in your report).
  • sorting information.
  • other related properties.

Crystal ActiveX Control properties can be changed either at design time or at runtime. Note, however, some properties are available only at runtime. These properties do not appear in the Properties list at design time.

Note: For a complete description of each property in the Crystal ActiveX Control, refer to the Crystal ActiveX Control Reference in the Techrefvol2.pdf.


Changing Properties for the ActiveX Control

  1. Click the ActiveX control on your form to select it.
  2. Right-click and choose Crystal Properties from the shortcut menu.

    The Property Pages dialog box appears.

  3. Use the tabs and controls in this dialog box to change the ActiveX Control properties at design time.

Note: ActiveX Control properties also appear in the Visual Basic Properties list box. For instructions on using the Properties list box, refer to your Visual Basic documentation.


Changing Properties at Runtime

You can set most of the ActiveX Control properties at runtime by adding simple entries to your procedure code. Runtime property settings replace settings you make via the Properties list at design time.

Use the Action property or the PrintReport method to actually process the report at runtime. The Action property and the PrintReport method can only be used at runtime, and are the only means by which a report can actually be generated by the ActiveX Control.

For information on how to set ActiveX Control properties at runtime, refer to their syntax by searching for each property by name in the Crystal Reports Developer's Help (CrystalDevHelp.chm). Included are examples of how to set each property at runtime.


Crystal Report Engine Automation Server

The Crystal Report Engine Automation Server has been designed as both an object-oriented approach to adding Crystal Report Engine features to your applications, and as an ideal method for displaying reports in web pages. If you work in a development environment that supports access to COM-based automation servers, such as Visual Basic, you will quickly make full use of the Crystal Report Engine Automation Server to add powerful reporting to your applications. In addition, if you manage a web server that supports Active Server Pages, such as Microsoft's Internet Information Server (IIS) or Personal Web Server, the Crystal Report Engine Automation Server satisfies all of your dynamic reporting needs.

The Crystal Report Engine Automation Server (CPEAUT32.DLL) was installed in your \WINDOWS\SYSTEM directory when you installed Crystal Reports. The Crystal Report Engine Automation Server is an in-process automation server based on the Component Object Model (COM). This automation server provides an IDispatch interface, but is not programmable through a vtable interface. For Visual Basic programmers and in Active Server Pages, handling the IDispatch interface is almost transparent. For more information on the Component Object Model and COM interfaces, refer to Microsoft documentation.

The following topics are discussed in this section:

  • Adding the Automation Server to your Visual Basic Project
  • Using the Automation Server in Visual Basic
  • Object Name Conflicts
  • Viewing the Crystal Report Engine Object Library
  • Handling Preview Window Events
  • Distributing the Automation Server with Visual Basic Applications
  • Sample Applications


Adding the Automation Server to your Visual Basic Project

Before you can use the Crystal Report Engine Automation Server with a Visual Basic project, it must be registered on your system, and you must add it to your project. If you selected to install Development Tools when you installed Crystal Reports, the automation server will have already been registered on your system. If you did not select Development Tools, run the Crystal Reports setup application again, select Custom installation, and make sure Development Tools are installed.

Note: The following procedures demonstrate the use of the Report Engine Automation Server in versions 5.0 and later of Visual Basic. For information on using automation servers in earlier versions of Visual Basic, or in other development environments, please refer to the documentation that came with your software.

To add the automation server to a project in Visual Basic versions 5.0 or 6.0:
  1. With your project open in Visual Basic, choose References from the Project menu. The References dialog box appears.

    Note: For complete information on adding ActiveX components to a project, refer to your Visual Basic documentation.

  2. The Available References list box shows all available component object libraries currently registered on your system. Scroll through this list box until you find the Crystal Report Engine 8 Object Library. This is the Crystal Report Engine Automation Server.

    Note: If the Crystal Report Engine Object Library does not appear in the Available References list box, use the Browse button to locate and select the Crystal Report Engine Automation Server (CPEAUT32.DLL) in your \WINDOWS\SYSTEM directory.

  3. Toggle on the check box next to the Crystal Report Engine 8 Object Library reference. This makes the Crystal Report Engine Automation Server available to your project.
  4. Click OK in the References dialog box.


Using the Automation Server in Visual Basic

There are five primary steps to using the Crystal Report Engine Automation Server in your Visual Basic project:

  • Creating an Application Object
  • Obtaining a Report Object
  • Using the Report Object
  • Releasing Objects
  • Handling Errors


Creating an Application Object

The Application object in the Crystal Report Engine Automation Server's object library is the only object that can be created. Using the Application object, you can obtain a report object by opening a report file, manipulate aspects of the report object, such as select formulas and sort fields, then print or export the report.

Since the Application object is the only creatable object exposed by the Crystal Report Engine Automation Server, you must create an Application object before you can perform any other tasks using the Crystal Report Engine. Use code similar to the following to create an Application object in your Visual Basic project:

Dim app As CRPEAuto.Application

Set app = CreateObject("Crystal.CRPE.Application")

Alternately, you can use the following code:

Dim app as New CRPEAuto.Application

Crystal.CRPE.Application is the Application object's ProgID (programmatic identifier). Visual Basic uses this ID to create an instance of the Application object, which can then be used to obtain a Report object. For a complete description of the CreateObject function, refer to your Visual Basic documentation.


Obtaining a Report Object

You obtain a Report object by specifying a Crystal Reports (.RPT) file and opening it with the OpenReport method of the Application object:

Dim report As CRPEAuto.Report

Set report = app.OpenReport("c:\reports\xtreme.rpt")

The OpenReport method has only one parameter, the path of the report file you want to access. By setting a report object according to the return value of this method, you can proceed to manipulate, print, preview, or export the report using other objects, methods, and properties available in the Crystal Report Engine Automation Server's object library.


Using the Report Object

Once you obtain a Report object, you can use that object to make runtime changes to the report file, then send the report to a printer, a preview window, a disk file, an e-mail address, an ODBC data source, or a group folder in Microsoft Exchange or Lotus Notes. Note that the changes you make at runtime are not permanent; they do not change the original report file, they only affect the output of the report during the current Crystal Report Engine session.

Through the report object, you obtain access to different aspects of the report file, such as selection formulas, subreports, sort fields, and format settings. For example, the following code changes the record selection formula for the report:

report.RecordSelectionFormula = "{customer.Region} = 'CA'"

Refer to the reference section of this manual for complete information on all objects, properties, and methods available in the object library and how to use them.

Once you make all desired changes and review settings for the report using the functionality available in the automation server, you can print, preview, or export the report just as you do from Crystal Reports. The automation server provides default settings for these activities, or you can specify your own settings. The simplest technique for sending the report to a printer would look like this:

report.PrintOut

Without receiving any parameters, the PrintOut method simply sends the report to the default printer with default settings. For more information about methods for the Report object, search for each method by name.


Releasing Objects

Visual Basic will clean up any objects that have not been released when your application terminates. However, since objects use memory and system resources that cannot be accessed by other running applications, you should get into the habit of releasing any objects when you are finished with them.

To release an object, simply set it equal to Nothing:

Set report = Nothing
Set app = Nothing


Handling Errors

Error trapping for the Crystal Report Engine Automation Server can be handled just like normal error trapping in Visual Basic. When an error occurs in the automation server, the error is sent to Visual Basic which sets the properties of the Err object appropriately. To avoid runtime problems, you should trap for errors inside your Visual Basic code. A typical error trapping routine might look something like this:

On Error GoTo HandleError

' Several lines of

' Visual Basic code

HandleError:

    If (Err.Number <> 0) Then

        MsgBox (Err.Description)

    End If

The advantage of handling automation server errors like this is that they can be handled at the same time other Visual Basic errors are handled, making your code more efficient and easier for other developers to understand.


Object Name Conflicts

Some object names in the Crystal Report Engine Object Library may conflict with object names in other object libraries attached to your Visual Basic projects. For instance, if your project includes the Data Access Objects (DAO) Object Library, the DAO Database object can conflict with the Report Engine Object Library's Database object. Another common name conflict can occur between the Report Engine's OLEObject and the RichTextLib OLEObject control. Such name conflicts can produce errors in your applications.

Note: RichTextLib is a component included with some versions of Visual Basic.

To avoid name conflicts, you should append all references to Crystal Report Engine Object Library object names with CRPEAuto, the name of the object library as it appears in Visual Basic. For instance, the following code can be used to create a Report object:

Dim rpt As CRPEAuto.Report

Set rpt = app.OpenReport("c:\reports\xtreme.rpt")

Object names in other object libraries should also be appended with an object library name. For instance, the DAO Database object could be appended with DAO:

Dim db As DAO.Database


Viewing the Crystal Report Engine Object Library

The Visual Basic Object Browser allows you examine the classes, methods, and properties exposed by any ActiveX component available to your project. If you have selected the Crystal Report Engine Object Library using the References dialog box (see Adding the Automation Server to your Visual Basic Project), then you can browse through the Object Library using the Visual Basic Object Browser:

  1. With your project open in Visual Basic, choose Object Browser from the View menu. The Object Browser appears.
  2. From the Libraries/Projects drop-down list, select the Crystal Report Engine Object Library. Classes, methods, and properties exposed by the Object Library will appear in the Object Browser.
  3. Select a class in the Classes/Modules list box to view its methods and properties in the Methods/Properties list box.

Note: While viewing the Crystal Report Engine Object Library in the Visual Basic Object Browser, you may notice several classes, methods, and properties that are not documented in the Crystal Reports Technical Reference. There are several features in the Crystal Report Engine Automation Server that are not available with Crystal Reports, and are protected by a security feature built into the Object Library. These features will become available in future Seagate Software products. Contact Seagate Software's Sales department for further information.

Crystal Reports also provides the Crystal Report Engine Object Library Browser Application as a convenient utility for accessing online information about the Crystal Report Engine Object Library. Simply choose the Xtreme Mountain Bike option in the Sample Files when installing, or choose an automatic installation (the files will be installed by default) to install the utility, then browse through the Object Library using the tree control. Select a class, method, or property for more information on how to use it.


Handling Preview Window Events

The Report and Window objects in the Crystal Report Engine Object Library include several Events. By handling these events in your Visual Basic project, you can customize how your application responds to user actions. For instance, if a user clicks on a button in the toolbar of the preview window, such as the Zoom button or the Next Page button, your application can respond to that event.

Note: Events are only available in Visual Basic 5.0 and later. If you are using a version of Visual Basic earlier than 5.0, you will not be able to make use of the Events exposed by the Report or Window object.

To handle Events for the Report or Window object, you must declare the instance of the object as Public and WithEvents. For example:

Public WithEvents repEvents As CRPEAuto.Report
Public WithEvents wndEvents As CRPEAuto.Window

Once declared, the objects will appear in the Visual Basic Object window. If you select the object, its Events will be displayed, just as if you were working with any other Visual Basic object.

Note: The Window object events are only valid when a report is sent to a preview window using the Preview method.

The following code demonstrates how to set up and use events for both the Report object and the Window object. Actual event handling code is left for you to fill in. You are limited only by the restrictions of the Visual Basic language.

Option Explicit
Public WithEvents rpt1 As CRPEAuto.Report

Public vw1 As CRPEAuto.View

Public WithEvents wnd1 As CRPEAuto.Window
Private Sub Command1_Click()

    Set vw1 = rpt1.Preview

    Set wnd1 = vw1.Parent

End Sub
Private Sub Form_Load()

    Set app1 = CreateObject("Crystal.CRPE.Application")

    Set rpt1 = app1.OpenReport("c:\crw\rt01.rpt")
    rpt1.EventInfo.ActivatePrintWindowEventEnabled = True

    rpt1.EventInfo.ClosePrintWindowEventEnabled = True

    rpt1.EventInfo.GroupEventEnabled = True

    rpt1.EventInfo.PrintWindowButtonEventEnabled = True

    rpt1.EventInfo.ReadingRecordEventEnabled = True

    rpt1.EventInfo.StartStopEventEnabled = True
End Sub
Private Sub rpt1_Start(ByVal Destination As _

                CRPEAuto.CRPrintingDestination, _

                useDefault As Boolean)
    ' Put event handling code here.
End Sub
Private Sub rpt1_Stop (ByVal Destination As

                CRPEAuto.CRPrintingDestination,

                ByVal Status As CRPEAuto.CRPrintingProgress)
    ' Put event handling code here.
End Sub
Private Sub wnd1_ActivatePrintWindow()
    ' Put event handling code here.
End Sub
Private Sub wnd1_ClosePrintWindow (useDefault As Boolean)
    ' Put event handling code here.
End Sub
' Other events for the Report and Window objects

' can be seen by using the Visual Basic Object Browser

' with the Crystal Report Engine Object Library.

' (a lightning bolt icon appears next to Events in

' the Object Browser.)
' Once and instance of a Report object or Window object,

' is declared, you can add Event handlers to your code by

' selecting the object in the Visual Basic Object list and

' then selecting the desired event.

For complete descriptions of all available Crystal Report Engine Object Library Events, refer to the Report Object and the Window Object.

Note: In the previous version of Crystal Reports a report or window object variable declared WithEvents could only be Set once. A VB error occurred if you tried to Set the variable to a different value(i.e. access a new report or display a new Preview window). This problem no longer exists. You can now reset the values of WithEvent object variables.


Distributing the Automation Server with Visual Basic Applications

When you finish designing your application and decide to distribute it to your users, you must make sure that the Crystal Report Engine Automation Server is distributed with it. In addition, you must make sure the automation server gets registered on your users' systems. The easiest way to do this is to use the Application Setup Wizard installed with Visual Basic.

This Wizard leads you through the process of designing a setup application for your project. In addition, the Setup Wizard detects any ActiveX components included in your project and leads you through the process of adding code to the setup application to include the required files and register the components on a user's machine.

For more information about files that need to be distributed with Crystal Report Engine applications, refer to License Manager Help (License.hlp).


Sample Applications

Crystal Reports includes a complete sample application written in Visual Basic 5.0 using the Crystal Report Engine Automation Server. The Xtreme Mountain Bike Inventory Application is a complete real-world application that provides various reports to employees at a fictitious company. Report access is restricted based on user logon information. The application is located in \Program Files\Seagate Software\Crystal Reports\sample\Xtreme\Inventory and provides the option of viewing the source code for any Visual Basic form displayed.

In addition, a self-extracting executable located in the \Program Files\Seagate Software\Crystal Reports\sample\sam32aut (or sam16aut) directory contains three small sample applications that demonstrate various aspects of the Crystal Report Engine Automation Server. Simply run the SAM32AUT.EXE application to install the samples. The three samples are:

  • AUBASIC
    Demonstrates the basic code required to open a report and print, preview, or export it using the Crystal Report Engine Automation Server.
  • AUBROWSE
    Demonstrates how to browse through the areas of a report and access the objects in each area.
  • AUFMLA
    Demonstrates how to get and set record selection formulas, group selection formulas, and SQL queries stored with a report.


Grid Controls and the Crystal Report Engine

In Crystal Reports, a Crystal ActiveX Control can be bound directly to a Visual Basic Data Control. Using the Visual Basic Data Control with the Crystal ActiveX Control offers the following benefits:

  • Generating reports in Visual Basic programs is made even easier and does not require an existing .RPT file.
  • A powerful feature of Visual Basic is ad-hoc queries that are run by executing SQL statements in the RecordSource property of the Data Control. By directly binding a Crystal Custom Control to a Data Control, users can now create reports of dynaset data which are the results of such ad-hoc queries.

The following topics are discussed in this section:

  • Bound Report Driver and Bound Report Files
  • Crystal ActiveX Control Properties
  • Creating a Bound Report using the Crystal ActiveX Control
  • Creating a Formatted Bound Report
  • Creating a Formatted Bound Report at Runtime
  • Sample Application


Bound Report Driver and Bound Report Files

When using Crystal Reports to generate reports from database files of a particular file format (for example, Paradox file format), you need to have the appropriate report driver (i.e., PDBPDX.DLL) to retrieve data from the databases. Similarly, when you generate reports by binding to a Visual Basic Data Control, a Bound Report Driver (PDBBND.DLL) is used to retrieve data from the Data Control. Make sure PDBBND.DLL is in your \WINDOWS\SYSTEM directory or search paths, along with other database drivers.


Crystal ActiveX Control Properties

Several properties are added to the Crystal Custom Control in order to support bound reports. These new properties are described below.

Custom

This property allows you to create bound .RPT files at Visual Basic design time and is not available at runtime. After a bound .RPT file is created, programmers can then use Crystal Reports to customize the report layout or even link the bound data to other database tables.

DataSource (Data Control)

This property can be read/write at design time and runtime. This property is ignored if the ReportSource property is 0 (Report files). To generate bound reports, set this property to the Data Control you want to retrieve data from. The Data Control must already be on the form before this property can be set.

BoundReportFooter (Boolean)

This property can be read/write both at design-time and runtime. This property is ignored if the ReportSource property is 0 (Report files). Default is False and the bound reports generated will not have page numbers printed. If set to True, page numbers will be printed at the bottom of a page.

BoundReportHeading (string expression)

This property can be read/write both at design time and runtime. This property is ignored if the ReportSource property is 0 (Report files). It specifies the report title at the beginning of a bound report. If it is blank, no report title will be printed.

ReportSource (numeric expression)

This property can be read/write both at design time and runtime. The allowed values are:

0 - Report files

1 - Bound TrueDBGrid Control

3 - All Data Control Fields

The default value is 0 - Report files, and the ReportFileName property must be assigned to an existing report path name (.RPT). This is equivalent to when the new bound report features were not available and all reports were generated from existing .RPT files.

When set to 1 or 3, the ReportFileName property will be ignored and no .RPT file is needed. Reports will be created using data retrieved from Data Control. The reports generated directly from the Data Control are identical to the reports generated from the respective bound .RPT files created using the (Custom) property described above.


Creating a Bound Report using the Crystal ActiveX Control

  1. Add the following controls to your Visual Basic form:
  2. On the Data Control:
      • Set the DatabaseName property to the name of the database being reported on.
      • Set the RecordSource property (this can be a database table or a SQL query statement).
  3. On the Crystal ActiveX Control:
      • Set the DataSource property to the Data Control (for example, Data1).
      • Set the ReportSource to 3 - All Data Control Fields.
  4. On the Command Button, add the following code for the Click event:
Private Sub Command1_Click()

    CrystalReport1.Action = 1

End Sub

Run the application, click the command button, and the Crystal ActiveX Control will retrieve data from the Data Control and create the report. The report will appear as a simple columnar report. There are no runtime properties to control any report formatting. However, this can be accomplished at design-time by editing the report designed by the ActiveX control (a report template) in Crystal Reports.


Creating a Formatted Bound Report

  1. Add the Data control, ActiveX control, and a command button to your form.
  2. On the Data control, set the DatabaseName property and the RecordSource property as you did in the previous example.
  3. On the ActiveX control:
      • Set the DataSource property to the Data Control (i.e., Data1).
      • Set the ReportSource property to 3 - All Data Control Fields.
      • Open the Custom property and select the Data-Bound Report Tab.
      • Click the Save Report As button and enter a name for the report.
  4. Open the report template in Crystal Reports and apply any formatting that you want including spacing between columns, font size, colors, grouping, and totaling. Save the report template again when finished.
  5. In your Visual Basic application, set the following properties for the ActiveX control:
      • Set the ReportSource to 0 - Report File.
      • Set the ReportFileName to the .RPT file that you saved (include the complete path of the file).
  6. On the command button, add the following code to the Click event:
Private Sub Command1_Click()

    CrystalReport1.Action = 1

End Sub

Now, the application will create the report at runtime with the formatting you have applied.


Creating a Formatted Bound Report at Runtime

The following steps describe an alternative method of creating formatted bound reports:

  1. Create your Visual Basic application as in the first example above.
  2. Set the ActiveX Control to print to a preview window, and run the application.
  3. Click the Export button in the preview window, and export the report to a disk file in .RPT format.
  4. Once the report has been exported, you can open it up in Crystal Reports.
  5. Perform all formatting changes that you want and save the report.
  6. Return to the Visual Basic application and stop it if it is still running.
  7. On the ActiveX Control:
  8. Set the ReportSource to 0 - Report File.
  9. Set the ReportFileName to the .RPT file that you created.
  10. Run the Visual Basic application and you will be able to see your bound report with the formatting changes you've made.

Note:

  • When creating formatted reports for use with the bound data control in Visual Basic, you will not be able to refresh the data from within Crystal Reports since the data does not exist outside of the Visual Basic application.
  • If you plan on using a formatted bound report, you will not be able to modify anything in the SELECT statement of the data control. The report needs all these fields and will fail if they are not all there. The formatted report cannot report on any new fields.

When passing properties at runtime using bound reports (i.e., SortFields), the syntax is slightly different. For example, the following syntax would be used for the Formulas and SortFields properties in a normal report:

CrystalReport1.Formulas(0) = "COMMISSION= {TableName.FIELDNAME}"
CrystalReport1.SortFields(0) = "+{TableName.FIELDNAME}"

However, for a bound report, the following syntax would be used:

CrystalReport1.Formulas(0) = "COMMISSION= {Bound Control.FIELDNAME}"
CrystalReport1.SortFields(0) = "+{Bound Control.FIELDNAME}"


Sample Application

Crystal Reports includes a complete sample application written in Visual Basic 5.0 using the Crystal Report Engine Automation Server and the Microsoft Data Bound Grid control. The Xtreme Mountain Bike Inventory Application is a complete real-world application that provides various reports to employees at a fictitious company. The Microsoft Data Bound Grid control is used for an order-entry page that dynamic reports are produced from. The application is installed, by default, in the \Program Files\Seagate Software\Crystal Reports\sample\Xtreme\Invntory directory.


Crystal Report Engine

The Crystal Report Engine is used alone and as a base class for other Crystal Reports development tools, including the Crystal ActiveX Control, Crystal Report Engine Automations Server, and the Crystal Visual Component Library. In this section you will find a general overview of how the Crystal Report Engine is used in an application, as well as a detailed section on the Crystal Report Engine API and it's most common functionality.

Click the appropriate link to jump to that section:

  • Introduction to the Crystal Report Engine
  • Crystal Report Engine API
  • Working with Parameter Values and Ranges
  • Working with section codes
  • Crystal Report Engine API variable length strings
  • Handling preview window events
  • Distributing Crystal Report Engine applications
  • Additional sources of information


Introduction to the Crystal Report Engine

Crystal Reports is a powerful stand-alone report creation application, as well it provides a report writing module that you can add to your own applications. As a developer using C, C++, Visual Basic, ObjectVision, Turbo Pascal, Visual dBASE, Delphi, or any programming language that can access a DLL, you can add sophisticated report generating and printing capabilities to your applications without the time-consuming task of writing your own code.

The Crystal Report Engine is a Dynamic Link Library (DLL) that allows your applications to access the same powerful report printing features that are available in Crystal Reports. As a licensed user of Crystal Reports, you receive royalty-free rights to ship the Crystal Report Engine DLL (CRPE.DLL or CRPE32.DLL) and all of its support files with any application you create.

Note: For more information regarding current runtime file requirements, see the Crystal Reports Developer Runtime Help (Runtime.hlp).

From your application, you can access the Crystal Report Engine through any of several Crystal Report Engine development tools:

  • Crystal ActiveX Controls (CRYSTL32.OCX)
  • Crystal Report Engine Automation Server (CPEAUT.DLL or CPEAUT32.DLL)
  • Crystal Visual Component Library in the Techrefvol2.pdf (UCRPE.DCU or UCRPE32.DCU)
  • The Crystal Report Engine Class Library (PEPLUS.H and PEPLUS.CPP)
  • The Crystal NewEra Class Library
  • Crystal Report Engine API (CRPE32.DLL)

When your application runs, it links with the Crystal Report Engine to access report writing functionality. Reporting can be simple, producing only a single report that is sent to a printer or preview window with no options available to the user, or it can be complex, allowing the user to change such things as record selection, sorting, grouping, or export options.


Sample Applications

Crystal Reports comes with a number of sample applications that show you how to incorporate the capabilities of the Crystal Report Engine. Use these applications to further your understanding of the Crystal Report Engine and how to use it in various programming environments.


SQL and ODBC

The Crystal Report Engine is fully compatible with most popular SQL DBMS applications, including Sybase SQL Server, Oracle, Gupta SQLBase, and Microsoft SQL Server. The Crystal Report Engine includes options for logging on to and off of SQL servers and ODBC data sources and also includes the ability to edit the SQL statement passed through to an SQL or ODBC database.


Exporting Reports

The Crystal Report Engine enables you to print to a printer or a preview window with simple function calls. In addition, you can export a file in multiple formats and to multiple destinations. For example:

  • through e-mail to another person or group of people
  • directly to disk
  • to HTML for updating a web site
  • to a Microsoft Exchange folder
  • to a Lotus Notes folder
  • to an ODBC data source

The report can be exported in any of several word processing, spreadsheet, database file, or data exchange formats including HTML.


Before using the Crystal Report Engine in your application

Before you add the Crystal Report Engine to your application, you should be familiar with some key features of the Crystal Report Engine. Review the following points, and make sure you understand each before attempting to make calls to the Crystal Report Engine from your application.

  • The Crystal Report Engine outputs existing reports. You cannot create report files using the functionality of the Crystal Report Engine. Reports must be created using the Crystal Reports application described in the Crystal Reports User's Guide. Make sure you understand the report creation process before trying to print reports with the Crystal Report Engine.

Note: Visual Basic programmers can use the Active Data Driver, along with the Crystal Report Engine API or the Crystal Report Engine Automation Server to create reports dynamically at runtime. For more information, refer to Active Data.

  • The Crystal Report Engine provides a convenient add-on to your existing application development project. With just a few lines of code, you can produce a powerful report writing and distribution tool that would take thousands of lines of code and weeks to produce otherwise.
  • The Crystal Report Engine does not require the use of a fixed user interface. The Crystal Report Engine is designed to work with your existing development project and allows you to define the user interface your customers and users are familiar with and expect from your application.


Using the Crystal Report Engine

Any development project that incorporates the Crystal Report Engine requires three steps:

  • Step 1: Creating reports (The reports that your users access.)
  • Step 2: Designing the user interface that drives the Crystal Report Engine.
  • Step 3: Adding the Crystal Report Engine to your application.
Related topics:

Using the Crystal Report Engine API in Delphi

Step 1: Creating reports

Creating reports to include with your applications is identical to creating reports for your own use; there are no restrictions. Using the procedures outlined in the Crystal Reports User's Guide and Crystal Reports Online Help (crw.chm), create as many kinds of reports as you want to make available to your users. You can make the reports as simple or as sophisticated as your needs dictate.

While designing reports, though, keep in mind their ultimate destination. Some export formats do not support all of the formatting options available in Crystal Reports. For example, if you will be exporting reports to HTML to automatically update a web site, HTML may not support all of the fonts available on your system. This is not a limit of the Crystal Report Engine export functionality, but a limit of the HTML format itself.

If you are a Visual Basic programmer or you are using any development environment that supports Automation Servers, you may want to have reports dynamically designed for you at runtime using the Active data driver. For complete information on using the Active data driver, see Active Data.

Visual Basic programmers can also take advantage of the Visual Basic data control or the TrueGrid ActiveX control at runtime to dynamically produce report files. See Grid Controls and the Crystal Report Engine, for information on using these controls with the Crystal Report Engine.

Step 2: Designing the user interface that drives the Crystal Report Engine

The interface you develop to allow users to print reports is limited only by your needs and your imagination. The kind of user interface you select is unimportant to the Crystal Report Engine.

Common methods of using the Crystal Report Engine include a single menu command that produces a single report, a dialog box allowing several options for printing reports, or a completely separate front-end application that is called by your application. All are acceptable techniques, and each has its advantages. How you design your user interface can depend on any or all of the following:

  • The purpose of your application.
  • The types of reports your application will use.
  • The printing options you want to make available with those reports.
  • Whether your application will offer only one report or a choice of several reports.

Consider your application and your reporting needs carefully, and design a User Interface that will use the Crystal Report Engine most efficiently.

Step 3: Adding the Crystal Report Engine to your application

Several different Crystal Report Engine development tools can be used to add the Crystal Report Engine to your application:

  • Crystal ActiveX Controls
  • Crystal Report Engine Automation Server
  • Crystal Visual Component Library in the Techrefvol2.pdf
  • The Crystal Report Engine Class Library
  • The Crystal NewEra Class Library
  • Crystal Report Engine API

Be aware that you cannot use two or more of these tools in the same application. For example, you cannot create a Visual Basic application that contains the Crystal ActiveX control and also makes calls to the functions in the Crystal Report Engine API. You must choose one tool to implement the Crystal Report Engine in your project and stick with that tool.

When choosing a Crystal Report Engine tool, consider the following:

  • What is your development environment?
  • What is your programming ability?
  • Do you need to implement the entire Crystal Report Engine or just a few features of it?

For example, the Crystal Class Library for NewEra is specifically designed for Informix NewEra. Therefore, if you are programming in Visual Basic, the Crystal Class Library for NewEra is not an option. The Crystal Report Engine Class Library, on the other hand, is based on the Microsoft Foundation Class Library for C++. To use the Crystal Report Engine Class Library, you must be using a C++ development tool, and you must be using the MFC library.

If you are an experienced programmer, you might consider the Crystal Report Engine API or the Crystal Report Engine Class Library. Novice programmers, on the other hand, may want to take advantage of the easy-to-use features of the Crystal ActiveX control, or the Visual Component Library.

The Crystal Report Engine API consists of a large number of functions exposed directly from the Crystal Report Engine DLL. These functions provide a wide range of power and flexibility for adding report writing features to your own applications.

Although the examples in the following sections concentrate on the C programming language, the concepts should be studied by anyone using the API functions in any language. Additional information specific to Visual Basic programmers using the API can be found in Enhancements to the Crystal Report Print Engine API. Additional information for Delphi programmers is located in Using the Crystal Report Engine API in Delphi. If you wish to use a Crystal Report Engine development tool other than the Crystal Report Engine API, search for the name of the programming language or development environment you are using in Crystal Reports Developer's Help (CrystalDevHelp.chm).


Using the Crystal Report Engine API in Delphi

All versions of Delphi can make direct calls to the functions in the Crystal Report Engine API. The Delphi unit file crdelphi.pas includes complete declarations for all Report Engine API functions and records. When you need to add the Report Engine API to your own Delphi unit, simply add the Crystal Report Engine API unit to your project and refer to the unit in your uses clause. For example:

Uses

    crpe32;

The implementation section of the Crystal Report Engine API unit contains all of the Crystal Report Engine API functions defined as external and as part of the CRPE or CRPE32 DLL.

The Crystal Report Engine Index, includes Delphi declarations for all Report Engine API functions and records. In addition, the Crystal Reports Developer's Help (CrystalDevHelp.chm) includes Delphi sample code using many of the functions and records defined in crdelphi.pas. Crystal Report Engine Functions Sample Code in Delphi


Crystal Report Engine API

The Crystal Report Engine API (REAPI) is the most direct method of adding the Crystal Report Engine to your application project. The Crystal Report Engine itself is a Dynamic Link Library (DLL), and, therefore, exports its functionality in the form of DLL functions. These functions make up the Crystal Report Engine API.

The Crystal Report Engine DLL, CRPE32.DLL (32-bit), was installed in your \WINDOWS\SYSTEM directory when you installed Crystal Reports. This assures that the DLL is available to any application on your system that uses the Crystal Report Engine.

Note: For complete information on distributing Crystal Report Engine and other runtime DLLs with your application, refer to the Crystal Reports Developer Runtime Help (Runtime.hlp).

The process for loading a DLL and calling DLL functions is a well documented aspect of the Windows API. If you are not familiar with working with DLLs, please refer to Windows API documentation before attempting to use the Crystal Report Engine API. You may also want to consider one of the other methods described in this section for adding the Crystal Report Engine to your application.

The rest of this section assumes an understanding of DLLs and how to use them in a Windows application. It also assumes a basic understanding of the C language. The examples here are written in C, and do not cover the LoadLibrary, GetProcAddress, or FreeLibrary calls.

Many Windows development environments support direct calls to DLL functions, Visual Basic, Visual dBASE, and Delphi, for example. Refer to the documentation for your development environment for complete instructions on using a DLL. Your documentation may also cover instructions on how to translate C function calls to the language you use. Study your documentation, then review the steps described here for using the Crystal Report Engine in an application via the Crystal REAPI.


Declarations for the Crystal Report Engine API (REAPI)

Crystal Reports provides several source code files that declare the functions in the Crystal REAPI for several popular development languages. These files were installed in the Crystal Reports directory (\CRW by default) and are ready to be immediately added to your project. The following Crystal REAPI declaration files are available:

  • CRPE.H declares all Crystal Report Engine API functions for C/C++.
  • GLOBAL.BAS and GLOBAL32.BAS declare all Crystal Report Engine API functions for Visual Basic. For more information on using the Crystal Report Engine API with Visual Basic, see Enhancements to the Crystal Report Print Engine API.
  • CRPEDB.H declares several Crystal Report Engine functions for Visual dBASE. Because of limits in the dBASE language, not all Crystal Report Engine functions are available to dBASE programmers.
  • CRDELPHI.PAS and CRPE32.PAS declare all Crystal Report Engine API functions for Delphi. For more information on using the Crystal Report Engine API with Delphi, see Using the Crystal Report Engine API in Delphi.

Note: Functions can be declared on an individual basis, but unless you will only be using a few of the Crystal Report Engine functions in your code, it is easiest to simply copy one of the previously mentioned code files into your project directory and add it to your project.


Using the Crystal Report Engine API

The Crystal REAPI provides two options for processing and producing reports from within an application:

  • The Print-Only Link
  • The Custom-Print Link

The Print-Only Link is the fastest, easiest method for producing a report with the Crystal REAPI. A Print-Only Link, however, provides a very limited functionality. It allows a report to be printed on a default printer or previewed in a window on-screen. It does not allow you to customize a report in any way before printing it, though.

A Custom-Print Link, on the other hand, provides all the report processing power of Crystal Reports itself. By coding a Custom-Print Link into your application, you can change record selection, record sorting, group creation, group selecting, group sorting, exporting to disk files, e-mail, Exchange and Lotus Notes folders, ODBC data sources, selecting specific printers for printing, logging on to SQL servers and ODBC data sources, editing formulas, formatting report sections, and much more. A Custom-Print Link is, however, a more complex process to code than a Print-Only Link.

The first time you use the Crystal REAPI in your application project, you may want to start by coding a simple Print-Only Link to produce basic reporting functionality. As your project develops and you become more familiar with the Crystal REAPI, you can expand the reporting functionality with a Custom-Print Link.


The Print-Only Link

A Print-Only Link is performed using the PEPrintReport function. The PEPrintReport function provides basic report printing functionality and demonstrates basic techniques for calling Crystal Report Engine functions from your application.

PEPrintReport enables your application to print a report, to select the output device, either a default printer or a preview window, and to specify the size and location of the preview window if the report is printed to a window. This function does not enable you to customize the report (select the records to print, set the sort order, etc.) at print time. You can set those parameters at report design time (using the Crystal Reports Design Tab), but you cannot change them at print time through a Print-Only Link.

If the report is sent to a preview window, you should also use the PEOpenEngine and PECloseEngine functions with your Print-Only Link. PEOpenEngine and PECloseEngine allow you to control how long the preview window remains open. The window will remain open until the PECloseEngine function is called or the user clicks Close in the window. If PEOpenEngine and PECloseEngine are not used, and the report is sent to a preview window, the window will automatically close as soon as the report finishes processing.

Note: You may also want to get in the habit of using PEOpenEngine and PECloseEngine in all Print-Only Links, as they are required steps to coding a Custom-Print Link. If your code includes these functions when you design a Print-Only Link, advancing the application to use a Custom-Print Link in the future will be much easier.

Related topics

PEPrintReport Arguments

Example code for a Print-Only Link


PEPrintReport Arguments

PEPrintReport is declared in CRPE.H as follows:

short FAR PASCAL PEPrintReport (

        char FAR *reportFilePath,

        BOOL toDefaultPrinter,

        BOOL toWindow, char FAR *title,

        int left, int top,

        int width, int height,

        DWORD style, HWND parentWindow);

The following table describes each argument:

Parameter | Description
reportFilePath | The name of the report to be printed. Include the path if the report is not in the current directory. The report name can be hard-coded and unchangeable at runtime, or you can pass a string variable or character array as the result of a user choice.
toDefaultPrinter | If toDefaultPrinter is set to TRUE (1), the report is sent to a printer. The toWindow argument should be set to FALSE.
toWindow | If toWindow is set to TRUE (1), the report is sent to a preview window. The toDefaultPrinter argument should be set to FALSE.
title | The title that you want to appear in the window title bar. This argument can receive a string variable or a character array at runtime.
left | The position, in current screen coordinates, at which you want the left edge of the preview window to appear if the report is being printed to a window. Current screen coordinate measurements can be set within your application.
top | The position, in current screen coordinates, at which you want the top edge of the preview window to appear if the report is being printed to a window. Current screen coordinate measurements can be set within your application.
width | The width of your preview window, in current screen coordinates, if the report is being printed to a window. Current screen coordinate measurements can be set within your application.
height | The height of your preview window, in current screen coordinates, if the report is being printed to a window. Current screen coordinate measurements can be set within your application.
style | The style setting, as defined in WINDOWS.H. Style settings can be combined using the bitwise OR operator. These are standard Windows styles. Refer to Windows API documentation for complete information on window styles. Use 0 for default style settings.
parentWindow | Specifies the window handle for the parent window to be used for this preview window.

When designing a Print-Only Link using PEPrintReport, keep the following points in mind:

  • If toDefaultPrinter = True, and if you have specified a printer in the report using the Printer Setup command, PEPrintReport prints to the specified printer. Otherwise it prints to the Windows default printer. If you wish to override both the printer specified in the report and the Windows default printer, you will need to establish a Custom-Print Link and specify the printer using the PESelectPrinter function.
  • If toDefaultPrinter = True, you may enter null values for all of the remaining parameters except reportFilePath because they apply to printing to a preview window only. The title parameter requires a null string (i.e., ""), while the rest of the parameters will accept 0 (zero).
  • If parentWindow is null, Crystal Reports creates a top level window. The top left corner specified is relative to the origin of the screen.
  • If parentWindow is the handle of an MDI frame window, Crystal Reports creates a preview window that is an MDI child window with the top left corner relative to the origin of the frame window's client area.
  • If parentWindow is the handle of some other window, Crystal Reports creates a preview window that is a child of that window with the top left corner specified relative to the origin of the parent window's client area.
  • You can use the Windows constant CW_USEDEFAULT (-32768) as the value of left, top, width, and height to indicate a default position for the preview window.

If the preview window is a top-level window and the window style is defined as 0 (i.e., the final two parameters in the PEPrintReport call are 0, 0) or, if the preview window is an MDI child window and the window style is defined as 0, Crystal Reports uses the following default style:

(WS_VISIBLE | WS_THICKFRAME | WS_SYSMENU | WS_MAXIMIZEBOX |
WS_MINIMIZEBOX)

That is, the default window is a visible window with a thick frame that can be used for sizing the window. The window includes a system menu box, and maximize and minimize buttons.


Example code for a Print-Only Link

The first step in accessing the Crystal Report Engine is to load it into memory. This can be done just before PEPrintReport is called, when a dialog box that allows printing opens, or even when your application first starts.

Once the Crystal Report Engine is open, PEPrintReport can be called as a result of some user action, such as clicking a button on screen, or some internal application procedure.

Finally, once you are finished with the Crystal Report Engine, close it by calling PECloseEngine. If you have several print jobs, do not close the Crystal Report Engine until all print jobs are finished. Opening and closing the Crystal Report Engine uses processor time and should only be performed when necessary.

The following C code demonstrates a possible message handler for an application that provides Print-Only Link functionality through a button in a dialog box. Use this code as an example of how to perform a Print-Only Link.

short result;
switch (message)

{

    case WM_INITDIALOG:

        if (!PEOpenEngine())

            ; // Handle error

        return TRUE;
    case WM_DESTROY:

        PECloseEngine();

        return TRUE;
    case WM_COMMAND:

        switch (wParam)

        {

            case IDC_PRINTBUTTON:

                result = PEPrintReport (

                    "boxoffic.rpt",

                    FALSE, TRUE,

                    "My Report",

                    CW_USEDEFAULT,

                    CW_USEDEFAULT,

                    CW_USEDEFAULT,

                    CW_USEDEFAULT,

                    CW_USEDEFAULT,

                    hwndParent);

                if (result != 0)

                    return FALSE;

                return TRUE;

        }

        break;

}


The Custom-Print Link

A more advanced, and more powerful, method of using the Crystal Report Engine is through a Custom-Print Link. Establishing a Custom-Print Link gives you a great deal of control over your reports at runtime. For example, you can:

  • set or modify the report sort order,
  • set or modify the record selection and/or group selection formulas,
  • modify existing report formulas,
  • set or modify the database location,
  • capture and evaluate Crystal Report Engine errors,
  • export a report to a file, e-mail, Exchange or Lotus Notes folder, or ODBC data source,
  • log on to SQL servers and ODBC data sources,
  • format report sections,
  • and much more.

Note: The Crystal Report Engine allows you to add a selection formula and sort fields to a report at runtime, even if none existed in the report when it was designed. Report formulas created in the Crystal Reports Formula Editor, however, must be added when the report is created in Crystal Reports. A formula can be edited with the Crystal Report Engine, but cannot be added to an existing report from the Crystal Report Engine. Design your reports carefully, and keep this in mind when you create your application.

Related topics

Coding a Custom-Print Link

A Sample Custom-Print Link


Coding a Custom-Print Link

There are six required steps to coding a Custom-Print Link in your application. Each uses a different REAPI function. These steps are:

  • Custom-Print Link Step 1: Open the Crystal Report Engine (PEOpenEngine).
  • Custom-Print Link Step 2: Open a print job (PEOpenPrintJob).
  • Custom-Print Link Step 3: Set the output destination(PEOutputToPrinter, PEOutputToWindow,
    or PEExportTo).
  • Custom-Print Link Step 4: Start the print job (PEStartPrintJob).
  • Custom-Print Link Step 5: Close the print job (PEClosePrintJob).
  • Custom-Print Link Step 6: Close the Crystal Report Engine (PECloseEngine).

In addition to these six steps, you can add several optional tasks any time after Step 2, opening the print job, and before Step 4, starting the print job. These optional tasks include changing selection formulas, editing report formulas, selecting export options, and sorting report fields.

Some REAPI functions can be called at special times to retrieve information about the print job or Crystal Report Engine. For example, PEGetVersion retrieves the current version of the Crystal Report Engine being used and can be called at any time, even without the Crystal Report Engine being open. Another example, PEGetJobStatus, can be called after Step 4 to obtain information about the current status of a job being printed. For more information on all REAPI functions, see Crystal Report Engine Index or search for functions by name in Crystal Reports Developer's Help (CrystalDevHelp.chm).

Note: The steps described here apply to a single print job. It is possible to have more than one print job open at once.


Custom-Print Link Step 1: Open the Crystal Report Engine
Example
PEOpenEngine();
Description

This step starts the Crystal Report Engine and prepares it to accept a print job. The Crystal Report Engine must be open before a print job can be established. You should open the Crystal Report Engine before the user has a chance to try to print a report. For example, if your application uses a dialog box as the user interface to the Crystal Report Engine, open the Crystal Report Engine immediately after the dialog box is created at runtime. Your dialog box can allow the user to establish a print job and make changes to the report while the Crystal Report Engine is already open.

Every time the Crystal Report Engine is opened, it should be closed once your application is finished accessing it (Custom-Print Link Step 6: Close the Crystal Report Engine). For example, if you open the Crystal Report Engine when a dialog box is created, close the Crystal Report Engine when that dialog box is destroyed.


Custom-Print Link Step 2: Open a print job
Example
job = PEOpenPrintJob("BOXOFFIC.RPT");
Description

When you open a print job, the Crystal Report Engine returns a Job Handle for the print job. This handle is important to identifying the print job in the rest of your code.

To establish a print job, PEOpenPrintJob, requires the path and name of the report that is to be printed. This argument can be hard-coded into the function call, as in the example above, or you can prompt the user to choose a report for printing and pass a variable argument to the function.

To close a print job, refer to Custom-Print Link Step 5: Close the print job. In most cases, you should open the print job immediately before printing and close the print job as soon as the job is finished and the preview window is closed or printing is complete.


Custom-Print Link Step 3: Set the output destination
Example
PEOutputToWindow (job, ReportTitle, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT, 0, NULL);
Description

The Crystal Report Engine must know where to send the final report. The report can be printed to a printer, displayed in a preview window, exported to a disk file, exported to another database, or exported to an e-mail address. The example above sends the report to the preview window.

Although you can choose any of the several destinations for report output, you must establish a destination for the report to print. You can, however, write code in your application that allows your users to decide on a destination themselves.

Note: This step does not actually print the report, it only establishes a destination for the report when printed. The report is actually printed in Step 4 using the PEStartPrintJob function.

The following functions are available to establish a print destination:

  • PEOutputToWindow
    Printing a report to a window requires no other print destination code other than the function itself.
  • PEOutputToPrinter
    Printing a report to a printer requires no other print destination code other than the function itself. However, PESelectPrinter, can be used to select a printer other than the default printer at runtime. The PESelectPrinter function uses the Windows structure DEVMODE. For more information on this structure, refer to the Windows SDK.
  • PEExportTo
    The PEExportTo function works with the PEExportOptions Structure and several DLLs that control a report's export destination and format. The information required by PEExportTo can be set in your code at design time or it can work with options in your application to allow a user to specify export destination and format. If you would like to allow your users to set the destination and format of a report file, but you do not wish to program the interface to do this, use the PEGetExportOptions function to have the Crystal Report Engine provide dialog boxes that query the user for export information at runtime.


Custom-Print Link Step 4: Start the print job
Example
PEStartPrintJob(job, TRUE);
Description

This function actually sends the report to the output device indicated in Step 3. Once PEStartPrintJob, is called, the Crystal Report Engine begins generating the report. The Crystal Report Engine displays a dialog box that indicates the status of the report being generated. If the report is sent to the preview window, the window will appear as soon as PEStartPrintJob is called. The preview window can be closed by a call to PECloseWindow, by closing the Crystal Report Engine (as in Step 6), or by the user clicking the
Close button.

As a general rule, you should avoid making any formatting changes to a print job once you call PEStartPrintJob, especially if the report is being displayed in a preview window (via PEOutputToWindow). Formatting changes made to a report while it is still being generated and displayed in the preview window may produce undesired results, and can cause errors in the Crystal Report Engine.


Custom-Print Link Step 5: Close the print job
Example

PEClosePrintJob(job);

Description

Once the print job has completed, it can be closed using PEClosePrintJob. If you wish to make more changes to the report and print it again, you can do so before closing the job. However, once your application is finished with a report, it should close the print job to free up memory in the user's system.


Custom-Print Link Step 6: Close the Crystal Report Engine
Example

PECloseEngine();

Description

This function closes the Crystal Report Engine entirely. No other Crystal Report Engine functions relating to print jobs may be called once the Crystal Report Engine is closed. Therefore, you should keep the Crystal Report Engine open until it is no longer needed in your application. For example, if the Crystal Report Engine is accessed through a dialog box in your application, you should wait to close the Crystal Report Engine until the dialog box is exited and destroyed by Windows.


A Sample Custom-Print Link

The sample code below has been designed to demonstrate four of the six basic steps in establishing a Custom-Print Link using the C programming language. This example is based on the following scenario:

  • Using Crystal Reports, you have created a report called ORDER.RPT and saved it to the C:\CRW directory. This report is a listing of customer orders, and it is the only report your application will need to print.
  • In your application, you have created a Print Report menu command that opens a dialog box. The dialog box allows the user to select whether the report is printed to the printer or sent to a preview window. If the report is to be sent to the preview window, a Boolean variable called ToWindow, declared and initialized in another section of code not seen here, is given the value of TRUE. If the report is to just be sent straight to the printer, ToWindow is given the value FALSE.
  • In the Print Report dialog box, there is also a Print button that initializes the event procedure to generate and print the report. The Event code section below demonstrates how the Custom-Print Link can be coded in the Print button event procedure of your application.
  • PEOpenEngine is called when the dialog box is created, and PECloseEngine is called when the dialog box is destroyed. For this reason, these two steps are not included in the Custom-Print Link that appears below.

The topic titled Event code demonstrates the basic custom-print event procedure. This code includes If statements that check to see if an error has occurred during the call to the Crystal Report Engine. When an error occurs, you can easily handle the error in a separate routine or function. The event code below calls the function ReportError whenever an error occurs. ReportError is not a Crystal Report Engine function but is meant simply as an example of how to handle Crystal Report Engine errors. The code for ReportError appears in the section Error code.


Event code
short hJob;            /* print job handle */

BOOL bResult;
hJob = PEOpenPrintJob("C:\\CRW\\ORDER.RPT");

if (!hJob)

    {

    ReportError(hJob);

    return;

    }
if (ToWindow)

    {

    bResult = PEOutputToWindow(hJob,

            "My Report", CW_USEDEFAULT,

            CW_USEDEFAULT, CW_USEDEFAULT,

            CW_USEDEFAULT, 0, NULL);

    }

else

    {

    bResult = PEOutputToPrinter(hJob, 1);

    }

if (!bResult)

    {

    ReportError(hJob);

    PEClosePrintJob(hJob);

    return;

    }

if (!PEStartPrintJob(hJob, TRUE))

    {

    ReportError(hJob);

    }

PEClosePrintJob(hJob);

return;


Error code
void ReportError(short printJob)
    {
    short        errorCode;

    HANDLE        textHandle;

    short        textLength;

    char        *errorText;
    errorCode = PEGetErrorCode(printJob);
    PEGetErrorText (            printJob,

                &textHandle,

                &textLength);
    errorText = (char*)malloc(textLength);
    PEGetHandleString(textHandle,

                errorText,

                textLength);
    MessageBox(        hWnd, errorText,

            "Print Job Failed",

            MB_OK | MB_ICONEXCLAMATION);
    return;
    }


Code Evaluation

Seagate Software IMG Holdings, Inc.
http://www.seagatesoftware.com
Support services:
http://support.seagatesoftware.com


Event code

The following is an evaluation of the sample event code that appears above.

short hJob;            /* print job handle */

BOOL bResult;

This section declares two local variables that are important to the remainder of the code. The variable hJob will receive the handle to the print job that results from a PEOpenPrintJob call. This handle is required by most Crystal Report Engine functions. bResult will be given a TRUE or FALSE value as the result of several Crystal Report Engine calls. Any time bResult receives a FALSE value, an error has occurred.

hJob = PEOpenPrintJob("C:\\CRW\\ORDER.RPT");

This call opens the new print job according to the path and file name of the report that is to be printed. In this example, the report name is hard-coded in the Crystal Report Engine call. A user would have no choice as to which report is printed. This function could also accept a character array or a pointer to a character array as an argument, allowing you to give your users the opportunity to choose a specific report for printing. PEOpenPrintJob returns a handle to the new print job, hJob. This handle will be used in all of the subsequent Crystal Report Engine calls shown here.

if (!hJob)

    {

    ReportError(hJob);

    return;

    }

This if statement verifies whether a valid print job handle was received in the previous line of code. If PEOpenPrintJob returned a value of 0, the print job is invalid and an error is reported. For more information on processing Crystal Report Engine errors, see the Error code section that appears below.

if (ToWindow)

    {

    bResult = PEOutputToWindow(hJob,

            "My Report", CW_USEDEFAULT,

            CW_USEDEFAULT, CW_USEDEFAULT,

            CW_USEDEFAULT, 0, NULL);

    }

else

    {

    bResult = PEOutputToPrinter(hJob, 1);

    }

ToWindow acts as a Boolean variable that provides information from the user's decision as to whether this report will be printed to a preview window or to a printer. If ToWindow holds a TRUE value, then the user has decided to print the report to a preview window.

The if else code determines an output destination for the report based on the user's earlier decision. The PEOutputToWindow function prepares the Crystal Report Engine to create a preview window while PEOutputToPrinter directs the Crystal Report Engine to print the report to the default printer. (The printer used by the Crystal Report Engine can be changed with the PESelectPrinter function.) The variable bResult receives a FALSE value if an error occurs in either function call.

if (!bResult)

    {

    ReportError(hJob);

    PEClosePrintJob(hJob);

    return;

    }

Once the appropriate destination function is called, you must verify its success and report an error if bResult is FALSE. ReportError is the error handling routine. It is an internal function designed to process any errors that occur during a print job. The function is passed the current value of the hJob handle for use in analyzing errors. See Error Codes for information on processing errors.

Note: ReportError is not a Crystal Report Engine function, but specific to the code appearing here; it is meant only as an example of how to handle Crystal Report Engine errors.

Since a print job has been opened, you must close it after the error is reported using PEClosePrintJob. See below for more information on this function. Finally, the if statement causes a return after the error has been reported, thus ending the print job session.

if (!PEStartPrintJob(hJob, TRUE))

    {

    ReportError(hJob);

    }

PEStartPrintJob actually sends the print job to the printer or a preview window. If the report is printed to a window, PEStartPrintJob creates and opens the window according to the parameters set in the PEOutputToWindow function. If PEStartPrintJob fails (returns FALSE), an error is reported.

PEClosePrintJob(hJob);

Once the report has printed, this print job can be closed and another one can be started if needed. If the report has been printed to a preview window, PEClosePrintJob does not close the window. The preview window is closed when the Close button is clicked, the PECloseWindow function is called, or the PECloseEngine function is called.

return;

Now that the print job has finished, the event procedure can return, and the application can wait for the next user event to occur.


Error code
void ReportError(short printJob)

    {

Crystal Report Engine error processing can be most efficiently handled by a separate internal function, such as the one shown here, that is called during a print job. The Event code that is evaluated above calls the ReportError function whenever a Crystal REAPI function returns an error. The code for the ReportError function appears here as an example of how to access and evaluate Crystal Report Engine errors. The error number returned by PEGetErrorCode can be used to control how your application reacts to different types of Crystal Report Engine errors.

Note: The REAPI functions described here, PEGetErrorCode and PEGetErrorText, are specific to REAPI error handling. For complete descriptions of these functions, see Crystal Report Engine Index, or search for the functions by name in Crystal Reports Developer's Help (CrystalDevHelp.chm). The function PEGetHandleString is used to retrieve variable length strings generated by different REAPI functions.

    short        errorCode;

    HANDLE        textHandle;

    short        textLength;

    char        *errorText;

Completely processing any Crystal Report Engine error requires at least four variables like those above. While only errorCode will be needed to retrieve the Crystal Report Engine error number, the other three variables will all be needed to retrieve the actual error text.

    errorCode = PEGetErrorCode(printJob);

PEGetErrorCode returns a number associated with the error that has occurred. For a list of these error codes and their meanings, see Error Codes.

    PEGetErrorText (            printJob,

                &textHandle,

                &textLength);

    errorText = (char*)malloc(textLength);

    PEGetHandleString(textHandle,

                errorText,

                textLength);

The error text must be returned in the form of a handle to a variable length string. The handle is used, along with the PEGetHandleString function to obtain the actual error text and store it in a character array. This is a complicated process, and it should be examined carefully if your code is to work.

    MessageBox(        hWnd, errorText,

            "Print Job Failed",

            MB_OK | MB_ICONEXCLAMATION);

Once the error has been obtained, you can display error information to the user. This example simply opens a warning message box to alert the user of the problem. Using the error code and the error text, however, you can control Crystal Report Engine error messages any way that you find appropriate for your application.

    return;

    }

Once error processing is finished, you can return to processing the print job. If an error has occurred during the print job, however, then the print job should be terminated immediately after the error is processed. Review the evaluation of the event code above for ideas on how to terminate a print job after an error.


Working with Parameter Values and Ranges

Parameters can contain discrete values, ranges, or both discrete values and ranges together. The following discussion outlines how Crystal Reports handles parameter values and ranges.

Before retrieving a parameter current value or range, Call PEGetParameterValueInfo, to determine what type of value(s) are stored. PEParameterValueInfo, member hasDiscreteValues will contain one of the following three constants.

Constant | Description
PE_DR_HASRANGE | Only ranges are present.
PE_DR_HASDISCRETE | Only discrete values are present.
PE_DR_HASDISCRETEANDRANGE | Both discrete values and ranges are present. See guidelines below.

The functions listed below are used to add and retrieve parameter discrete values and parameter ranges. The sequence of functions that you call in your application will depend on whether discrete values, ranges, or a combination of both are present.

PEXXXParameterCurrentValue(s) | PEXXXParameterCurrentRange(s)
PEGetNParameterCurrentValues | PEGetNParameterCurrentRanges
PEGetNthParameterCurrentValue | PEGetNthParameterCurrentRange
PEAddParameterCurrentValue | PEAddParameterCurrentRange

Use the following guidelines when deciding which sequence of functions to call.

PEParameterValueInfo.hasDiscreteValues = PE_DR_HASRANGE

    • The parameter field contains only ranges.
    • All values will be treated as ranges.
    • Use the PEXXXParameterCurrentRange(s) function calls.

PEParameterValueInfo.hasDiscreteValues = PE_DR_HASDISCRETE

    • The parameter field contains only discrete values.
    • All values will be treated as discrete values.
    • Use the PEXXXParameterCurrentValue(s) function calls.

PEParameterValueInfo.hasDiscreteValues = PE_DR_HASDISCRETEANDRANGE

    • The parameter field contains both discrete values and ranges.
    • All values will be treated as ranges.
    • Use the PEXXXParameterCurrentRange(s) function calls.
    • You can also call PEAddParameterCurrentValue to add a discrete value, but the discrete value will be stored internally as a range and you will need to call PEGetNParameterCurrentRanges and then PEGetNthParameterCurrentRange when you want to retrieve it. If you try to retrieve the discrete value using PEGetNParameterCurrentValues, 0 will be returned.


Working with section codes

A report, by default, contains five areas: Report Header, Page Header, Details, Report Footer, and Page Footer. Each of those areas can contain one or more sections. When you add groups, subtotals, or other summaries to your report, the program adds Group Header and Group Footer areas as needed, and each of those areas can contain one or more sections as well. Since one report can have a totally different section configuration from the next, Crystal Reports uses calculated section codes to identify the sections in each report.

In Crystal Report Engine API functions that affect report sections, the sectionCode parameter encodes the section type, the group number (if the section is a Group Header or Group Footer section), and the section number (if there are multiple sections in an area) together in a single value.

The Crystal Report Engine API also includes macros for encoding section codes (PE_SECTION_CODE, for use with functions that require a section code) and for decoding section codes (PE_SECTION_TYPE, PE_GROUP_N, and PE_SECTION_N, for use with functions that return a section code). The examples that follow show how the encoding and decoding macros can be used.

Note: You cannot pass the above values directly to a function as section codes. You must use the encoding macro to create a valid section code based on one of the above constants.


Encoding

The PE_SECTION_CODE macro allows you to define a section code to pass as a parameter in Crystal Report Engine functions that require a section code. The syntax for the macro is:

PE_SECTION_CODE (sectionType, groupNumber, sectionNumber)

The PE_AREA_CODE macro allows you to define a corresponding area code. The following syntax is used:

PE_AREA_CODE(sectionType,groupN)


sectionType

This indicates the report area or section type that the section is in. For section type, use any of the following constants:

Section Type Constant | Value | Description
PE_SECT_REPORT_HEADER | 1 | Report Header Section
PE_SECT_PAGE_HEADER | 2 | Page Header Section
PE_SECT_GROUP_HEADER | 3 | Group Header Section
PE_SECT_DETAIL | 4 | Detail Section
PE_SECT_GROUP_FOOTER | 5 | Group Footer Section
PE_SECT_PAGE_FOOTER | 7 | Page Footer Section
PE_SECT_REPORT_FOOTER | 8 | Report Footer Section
PE_ALLSECTIONS | 0 | All Report Sections


groupNumber

Indicates which group the section is in. If the sectionType value indicated is PE_SECT_GROUP_HEADER or PE_SECT_GROUP_FOOTER, the groupNumber is a zero (0) based index for the group section. If the sectionType value is not one of these group section constants, the groupNumber value should always be zero.


sectionNumber

If the report area has been split into more than one section, sectionNumber indicates which section within the area you are using. This value is a zero (0) based index. In other words, the first section in an area is 0, the next section is 1, etc.

Note: The macro PE_SECTION_CODE calculates and returns the section code number; it does not return an error code.

The following example demonstrates how to obtain a section code using the PE_SECTION_CODE macro. The section code obtained here is for the second section in the Group Header 1 area:

code = PE_SECTION_CODE(PE_SECT_GROUP_HEADER, 0, 1);

PESetSectionFormat(job, code, &mySectionOptions);

In this case you pass the section type (PE_SECT_GROUP_HEADER), the group number (since this is the first group, use the zero indexed group number 0) and section number (since this is the second section in the Group Header, use the zero indexed section number 1). The program uses the encoding macro and returns a section code which is then passed in the PESetSectionFormat call.

When using PE_ALLSECTIONS in your macro, code can be written in one of
two ways:

code = PE_SECTION_CODE(PE_ALLSECTIONS, 0, 0);

// the code value returned is 0 - NOT an error code

PESetSectionFormat(job, code, &mySectionOptions);

or, you can eliminate using the macro all together:

PESetSectionFormat(job, PE_ALLSECTIONS, & mySectionOptions)

Note: The maximum number of groups is 25 (possible values of 0 to 24). The maximum number of sections is 40 (possible values of 0 to 39).


Decoding

Some Crystal Report Engine functions return section codes. These values can be decoded using one of three macros:

  • PE_SECTION_TYPE (sectionCode)
  • PE_GROUP_N (sectionCode)
  • PE_SECTION_N (sectionCode)

Each macro accepts an encoded section code as a parameter.

In the following example, you determine the number of sections in the report (using PEGetNSections), obtain the section code for each section (using PEGetSectionCode), and then decode the section code using the PE_SECTION_TYPE, PE_GROUP_N, and PE_SECTION_N macros.

numSections = PEGetNSections(job);

for (i = 0;i < numSections;i++)

{

    code = PEGetSectionCode(job, loopSectionN);

    areaType = PE_SECTION_TYPE(code);

    groupN = PE_GROUP_N(code);

    sectionN = PE_SECTION_N(code);

    // Perform section specific code here

}

Once you've identified the area, group, and section you want, you can then set the section format using code similar to this:

PESetSectionFormat(job, code, &mySectionOptions);

Note: Earlier versions of Crystal Reports used different section code constants. Those constants have been remapped to the new section code format so reports created with earlier versions of Crystal Reports can run with applications created with the current version.


Section Map

The following map shows the pattern of section code assignment:

Report Header
1000 | First Section in Report Header Area
1025 | Second Section in Report Header Area
1050 | Third Section in Report Header Area
1075 | Fourth Section in Report Header Area
up to 1975 | 40th Section in Report Header Area
Page Header
2000 | First Section in Page Header Area
2025 | Second Section in Page Header Area
2050 | Third Section in Page Header Area
2075 | Fourth Section in Page Header Area
up to 2975 | 40th Section in Page Header Area
GH1
3000 | First Section in First Group Header Area
3025 | Second Section in First Group Header Area
3050 | Third Section in First Group Header Area
3075 | Fourth Section in First Group Header Area
GH2
3001 | First Section in Second Group Header Area
3026 | Second Section in Second Group Header Area
3051 | Third Section in Second Group Header Area
3076 | Fourth Section in Second Group Header Area
Details
4000 | First Section in Details Area
4025 | Second Section in Details Area
4050 | Third Section in Details Area
4075 | Fourth Section in Details Area
GF1
5000 | First Section in First Group Footer Area
5025 | Second Section in First Group Footer Area
5050 | Third Section in First Group Footer Area
5075 | Fourth Section in First Group Footer Area
GF2
5001 | First Section in Second Group Footer Area
5026 | Second Section in Second Group Footer Area
5051 | Third Section in Second Group Footer Area
5076 | Fourth Section in Second Group Footer Area
Page Footer
7000 | First Section in Page Footer Area
7025 | Second Section in Page Footer Area
7050 | Third Section in Page Footer Area
7075 | Fourth Section in Page Footer Area
Report Footer
8000 | First Section in Report Footer Area
8025 | Second Section in Report Footer Area
8050 | Third Section in Report Footer Area
8075 | Fourth Section in Report Footer Area


Section Codes in Visual Basic

The following functions provide Visual Basic equivalents.


Create a section code:

This representation allows up to 25 groups and 40 sections of a given type, although Crystal Reports itself has no such limitations.

Function PE_SECTION_CODE(sectionType As Integer, groupN As Integer,
sectionN As Integer) As Integer
    PE_SECTION_CODE = (((sectionType) * 1000) + ((groupN) Mod 25) +
(((sectionN) Mod 40) * 25))
End Function


Create an area code:
Function PE_AREA_CODE(sectionType As Integer, groupN As Integer) As
Integer
    PE_AREA_CODE = PE_SECTION_CODE(sectionType, groupN, 0)
End Function


Decode a group number from a section code:
Function PE_GROUP_N(sectionCode As Integer) As Integer
    PE_GROUP_N = ((sectionCode) Mod 25)
End Function


Decode a section number from a section code:
Function PE_SECTION_N(sectionCode) As Integer
   PE_SECTION_N = (((sectionCode \ 25) Mod 40))
End Function


Decode a section type from a section code:
Function PE_SECTION_TYPE(sectionCode As Integer) As Integer
    PE_SECTION_TYPE = ((sectionCode) \ 1000)
End Function


Crystal Report Engine API variable length strings

Several REAPI functions provide information in the form of a variable length string value or character array. When your program calls an REAPI function that produces a variable-length string, the Crystal Report Engine saves the string, creates a string handle which refers to the string, and returns that handle along with a value indicating the length of the string. To retrieve the contents of the string, you must call PEGetHandleString. This approach allows you to allocate a buffer of the exact size needed to hold the string before obtaining the actual string.

If your development language cannot allocate a buffer at runtime, you should declare a reasonably large buffer. Field names and error messages will generally be less than 100 bytes, but formulas may be 1000 bytes or longer. You can control how much data is copied to the buffer when you call PEGetHandleString.

Here is the procedure to follow when obtaining a variable length string:

  1. Call-up the function which produces the string. This returns the string handle and length. The length includes all characters in the string plus a terminating null byte.
  2. If necessary, allocate the string buffer.
  3. Call-up PEGetHandleString to copy the string from the handle into the buffer.

Note: PEGetHandleString frees the memory occupied by the string handle, so you can only call this function once for a given handle.

Note: For experienced Windows programmers: text and name handles are Global Memory Handles for memory segments on the global heap. If you prefer, you can access these segments using the Windows GlobalLock, GlobalUnlock, and GlobalFree functions. Contents of name and text handles are null terminated ASCII strings. You must free the text handle with GlobalFree when you are done with it (PEGetHandleString does this for you, if you use it).


Sample Code

Use the following C code as an example of how to call a function that returns a variable length string. The code uses the var reportAlertInfo : PEReportAlertInfo) : boolean stdcall;, function which obtains the name of a field being used to sort the report and the direction of the sort. There are several other functions that return variable length strings, all of which are handled in a similar fashion.

Examine this code carefully and try to incorporate it into your own application without modifying the basic procedure. Only experienced programmers should try making changes to this technique since small mistakes here can cause major errors in your application. If you expect to use several REAPI functions that return variable length strings, you may want to set this code up in a separate function to avoid repetition and errors.

HANDLE         nameHandle;

short         nameLength;

short         direction;

char        *fieldName;
PEGetNthSortField (printJob, sortFieldN,

            &nameHandle, &nameLength,

            &direction);
/* allocate fieldName buffer */

fieldName = (char*)malloc(nameLength);
PEGetHandleString (                nameHandle,

                fieldName,

                nameLength);

/*

** fieldName now contains name

** of field and nameHandle is no

** longer valid.

*/

Note: If you retrieve a string handle but do not retrieve the string itself (i.e., you do not use PEGetHandleString), you should free up the string memory by calling GlobalFree (nameHandle).


Code Evaluation

HANDLE         nameHandle;

short         nameLength;

short         direction;

char        *fieldName;

Any time you evaluate a function that returns a variable length string, you will need at least three variables:

  • a handle to the string,
  • a short integer to hold the length of the string, and
  • a character array or pointer to a character array.

The direction variable in this example will hold the sort direction and is specific to PEGetNthSQLExpression.

It is important to note that although the PEGetNthSortField function is defined in the Crystal Report Engine as accepting a pointer to a handle (HANDLE*) and a pointer to a short (short*), nameHandle and nameLength are not defined as pointer variables. Instead, they are defined simply as a HANDLE and a short integer, then passed to PEGetNthSortField with the & operator. This technique automatically initializes the variables with the address of the variable itself. Since the PEGetNthSortField function requires the address in memory to place the information, this is the most convenient method to define and pass the variables.

PEGetNthSortField (printJob, sortFieldN,

            &nameHandle, &nameLength,

            &direction);

The PEGetNthSortField function places a handle to the sort field name in the nameHandle location and the length of the field name (all characters in the name plus a terminating null byte) in the nameLength location. These values will be used to extract the actual field name.

/*allocate fieldName buffer*/

fieldName = (char*)malloc(nameLength);

Now that you know the actual length of the field name you are trying to obtain, you can allocate exactly the right amount of memory to store that name. The malloc function does this.

Note: Malloc is defined in the C runtime library stdlib.h.

PEGetHandleString (                nameHandle,

                fieldName,

                nameLength);

PEGetHandleString, uses the string handle to retrieve the field name and store it in fieldName. At the same time, nameHandle is invalidated. Now, the text can be used like any other character string.

Note: This code is meant as a basis for your own code. Although these elements shown here are necessary for extracting a variable length string from certain Crystal Report Engine functions, experienced programmers may wish to expand the code to trap errors or handle the string text differently.

The following is a list of the Crystal REAPI functions that return variable length strings:

  • PEGetAreaFormatFormula
  • PEGetErrorText
  • PEGetFormula
  • PEGetGroupOptions
  • PEGetGroupSelectionFormula
  • PEGetNthFormula
  • PEGetNthGroupSortField
  • PEGetNthParameterField
  • var reportAlertInfo : PEReportAlertInfo) : boolean stdcall;
  • PEGetReportTitle
  • PEGetSectionFormatFormula
  • PEGetSelectedPrinter
  • PEGetSelectionFormula
  • PEGetSQLQuery


Crystal Report Engine API structures

Several REAPI functions require a structure or user-defined variable type to be passed as one or more arguments. Some of these functions require that you assign values to all members of the structure before calling the function so that the information can be used to make various settings in the Crystal Report Engine. Other functions require only the size of the structure be assigned to the StructSize member. These functions fill in the rest of the structure members for you, providing you with valuable information about a print job.

Note: The term structure is used here to mean both C structures and other user-defined types or records in languages such as Visual Basic and Delphi. If you are unfamiliar with this type of data, refer to the documentation for the programming language you are using.

Some of the structures, PEMouseClickEventInfo, for example, are complex, requiring other structures be passed as member values. Not all programming languages support this feature. If you are using a programming language that does not allow the use of a structure variable as a member variable defined inside other structures, declare the member variable as another data type, such as an integer or a variant data type, and assign it a value of 0 (zero) at runtime. The Crystal Report Engine will automatically provide default values or will request information from the user.

Note: Structure variables cannot be created using Visual dBASE. Crystal Report Engine functions requiring structures as parameters are not available to dBASE.


Working with subreports

Your application can have much of the same control over subreports that it has over primary reports. The only exceptions are:

  • you cannot open or close a print job while a subreport is open, and
  • you can only work with report sections that are actually in the subreport.

For example, subreports do not have page header sections like primary reports do, so you cannot do anything with a subreport that requires a page header section.

Most Crystal Report Engine functions require a print job handle as a parameter. When you supply the handle to a primary report, the functions act on the primary report. When you supply the handle to a subreport, the functions act on the subreport. Getting the handle requires a number of steps.


Opening the primary report

You must first open the primary report using the PEOpenPrintJob function. When you do this, the program returns a handle to the primary report.


Retrieving an interim subreport handle

You must then identify the subreport you want to open, using the PEGetNSubreportsInSection, and PEGetNthSubreportInSection, functions to do this. When you run the PEGetNthSubreportInSection function, the Crystal Report Engine returns an interim, double-word handle to the subreport you specified.


Retrieving the subreport name

Once you have the handle, use the PEGetSubreportInfo function to retrieve the name of the subreport. When you run this function, the double-word handle is passed as the subreportHandle argument. The program retrieves the subreport name as the name member of the PESubreportInfo) structure.


Opening the subreport and retrieving the job handle

Now that you have the name of the subreport (the name you assigned the subreport when you created it in Crystal Reports), use the PEOpenSubreport function to open the subreport. When using this function, you pass the name (or pointer to the name, depending on your development tool) as the subreportName argument. The program then opens the specified subreport and returns a job handle.


Running other Crystal Report Engine functions

Once you have the job handle, you can run any of the other Crystal Report Engine functions with the subreport, passing the subreport job handle as the printJob argument.


Changing report formats

When sending reports to a preview window using PEOutputToWindow, you should always avoid making any formatting changes to a print job once you call PEStartPrintJob. If the first page of a report has been displayed in the preview window, and you make formatting changes to the print job, subsequent pages of the report, if requested, may appear formatted differently than the first page. Depending on the changes made, trying to change report formatting after calling PEStartPrintJob can even cause errors in the Crystal Report Engine.

To avoid such formatting problems, you should get in the habit of formatting the report before starting the print job with PEStartPrintJob. Adding a routine to monitor job status using PEGetJobStatus, can also help avoid conflicts. If you need to display the same report with different formatting options, create two separate print jobs, format each separately, and start each separately.


Exporting reports

Using Crystal Reports, you can give your applications the ability to export reports in a number of word processor and spreadsheet formats, and in a variety of popular data interchange formats as well.

The program includes two export functions, PEExportTo, and PEGetExportOptions. PEExportTo can be used by itself or in conjunction with PEGetExportOptions.

  • Use PEExportTo by itself if you want your application to export reports in a fixed format to a fixed destination. Use this alternative, for example, if you want to preset the format and destination for a report and have the application export the report according to your specifications in response to user input.
  • Use PEExportTo in conjunction with PEGetExportOptions to export reports in the format and destination your user selects from the Export dialog box at Print time.

PEGetExportOptions can only be used in conjunction with PEExportTo.


PEExportTo overview

The PEExportTo function uses a structure, PEExportOptions, as part of its argument list. This structure passes format and destination data to the function.

When using the PEExportTo function by itself, you hard code the format and destination data into the structure. Then, when you issue a call to PEStartPrintJob, the program exports the report using the format and destination you specified in the code.

  • Most of the format and destination data that you need to enter can be taken from the table in the PEExportTo topic.
  • To hard code an export file name or e-mail header information, you will have to pass a second structure as an argument to the PEExportOptions structure. This second structure is defined in the *.h file that corresponds with the destination DLL you have selected.

When using the PEExportTo function in conjunction with the PEGetExportOptions function, you run the PEGetExportOptions function first to:

  • retrieve the format and destination data that the user specifies in the Export dialog box, and
  • pass that data to the PEExportOptions structure (again, part of the PEExportTo argument list).

Then, when you issue a call to PEEnableEvent, the program exports the report using the format and destination specified by the user.


PEExportOptions Structure

struct PEExportOptions

{

WORD StructSize;

    // the size of the structure. Initialize to sizeof PEExportOptions

char formatDLLName [PE_DLL_NAME_LEN];

    // Each export format is defined in a DLL. This is the name of the

    // DLL for the format you select. From table in PEExportTo topic.

    // Requires a null-terminated string. Does not need to include

    // drive, path or extension. For example, uxfsepv is an example of

    // a valid formatDLLName.

DWORD formatType;

    // Some DLLs are used for more than one format. Enter the

    // appropriate value from the table under PEExportTo.

void FAR *formatOptions;

    // Some formats offer additional options (see table in the

    // PEExportTo topic). You can set this element to 0. Then, If the

    // DLLs require more information, they will prompt the user

    // for it. To hard code this information, see the note immediately

    // following this structure.

char destinationDLLName [PE_DLL_NAME_LEN];

    // Each export destination is defined in a DLL. This is the name of

    // the DLL for the destination you select. From table in PEExportTo

    // topic. Requires a null-terminated string. Does not need to

    // include drive, path or extension. For example, uxddisk is an

    // example of a valid destination DLLName.

DWORD destinationType;

    // At the present time, each DLL implements only one destination.

    // You must specify a type here, nonetheless, because the DLL may

    // implement more than one destination someday. See the table under

    // PEExportTo for values to enter here.

void FAR *destinationOptions;

    // Some destinations offer additional options (see table in the

    // PEExportTo topic). You can set this element to 0. Then, If the

    // DLLs require more information, they will prompt the user for

    // it. To hard code this information, see the note immediately

    // following this structure.

WORD nFormatOptionsBytes;

    // Set by 'PEGetExportOptions', ignored by 'PEExportTo'. Both

    // functions use the same structure. PEGetExportOptions uses this

    // information in communicating with the application. The

    // application needs to know how many options bytes are being

    // returned because it may need to copy the options. PEExportTo

    // expects a filled in structure and does not need the byte

    // information because it is not going to copy the options. It uses

    // only a subset of the structure that does not include byte

       information.

WORD nDestinationOptionsBytes;

    // Set by 'PEGetExportOptions', ignored by 'PEExportTo'. See

    // comments for nFormatOptionsBytes above.

};

Note: You may choose to hard code the data for formatOptions and destinationOptions. You can set the formatOptions and destinationOptions elements to 0 as indicated. If the DLLs require more information than this, however, they will prompt the user to include more information. To hard code this information, you must define and fill in a structure of the appropriate kind. See the header file for the specified DLL for examples. Once the structure is defined, set the formatOptions or destinationOptions element to the address of the structure. Once PEExportTo returns or finishes, deallocate the formatOptions and destinationOptions structures. You should also deallocate the PEExportOptions structure once PEExportTo returns.


Considerations when using the export functions

The export functions are complex function calls. To avoid errors when exporting report files from your application, keep the following things in mind:

  • In order to use PEGetExportOptions and PEExportOptions, you must be using the version of the Crystal Report Engine (CRPE32.DLL) that came with the Professional Edition of Crystal Reports. If you have an earlier version of CRPE32.DLL installed on your machine and its earlier in the path, the program may find it first and not find the export functions. This can happen particularly if you are upgrading to the Professional Edition of Crystal Reports from the version of Crystal Reports that was shipped with Visual Basic Professional Edition. Visual Basic included an earlier version of CRPE32.DLL. Search your disk and delete or rename earlier versions of CRPE32.DLL, or make appropriate adjustments to your path statement.
  • Make sure all format DLLs and destination DLLs are located in the same directory as CRPE32.DLL. Once Windows finds CRPE32.DLL, it will expect all of the DLL files to be in the same directory. Format DLLs are all UXF*.DLL files and Destination DLLs are all UXD*.DLL files. As a general rule, it is best to keep all of these files in the \CRW directory or the directory into which you installed Crystal Reports. Also, make certain that the PATH statement in your AUTOEXEC.BAT file includes \CRW.
  • The UXF*.H and UXD*.H header files are only necessary when compiling your application. These files should be copied to the same directory as your application's source files.


Handling preview window events

Using the Crystal Report Engine API, you can create a Windows CALLBACK function to handle events that occur in a preview window. For instance, if a user clicks on a button in the toolbar of the preview window, such as the Zoom button or the Next Page button, Windows registers an event for the preview window.

Using the Event functions in the Crystal REAPI, you can add instructions to your own applications to perform specific actions according to events that occur in a preview window. The sample code below demonstrates how to handle preview window events by creating a CALLBACK function for the preview window, then initializing the preview window with that CALLBACK function in your Crystal Report Engine code. The code can handle toolbar button events, Group Tree events, and even drill-down events.

The Crystal Report Engine API Event functions are only valid when a print job is sent to a preview window using PEOutputToWindow.

#define  PE_ERR_INVALIDPARAMETERRANGEINFO 672
#include "crpe.h"

#include "Windows.h"
// The EventCallback function is defined as a standard

// Windows CALLBACK procedure. Return TRUE to allow the

// Crystal Report Engine to provide default behavior.

// Return FALSE to prevent default behavior from being carried out.
// The comment TODO indicates where you need to add event

// handling code specific to your application.
#if defined (WIN32)

BOOL CALLBACK EventCallback (short eventID,

                    void *param, void *userData)

#else

BOOL CALLBACK __export EventCallback (short eventID,

                        void *param, void *userData)

#endif

{
    switch(eventID)

    {

        case PE_CLOSE_PRINT_WINDOW_EVENT:

        case PE_PRINT_BUTTON_CLICKED_EVENT:

        case PE_EXPORT_BUTTON_CLICKED_EVENT:

        case PE_FIRST_PAGE_BUTTON_CLICKED_EVENT:

        case PE_PREVIOUS_PAGE_BUTTON_CLICKED_EVENT:

        case PE_NEXT_PAGE_BUTTON_CLICKED_EVENT:

        case PE_LAST_PAGE_BUTTON_CLICKED_EVENT:

        case PE_CANCEL_BUTTON_CLICKED_EVENT:

        case PE_ACTIVATE_PRINT_WINDOW_EVENT:

        case PE_DEACTIVATE_PRINT_WINDOW_EVENT:

        case PE_PRINT_SETUP_BUTTON_CLICKED_EVENT:

        case PE_REFRESH_BUTTON_CLICKED_EVENT:

        {

            PEGeneralPrintWindowEventInfo * eventInfo =

                (PEGeneralPrintWindowEventInfo *) param;

            ASSERT(eventInfo != 0 && eventInfo->StructSize ==

                PE_SIZEOF_GENERAL_PRINT_WINDOW_EVENT_INFO);
            // TODO
        }

            break;
        case PE_ZOOM_LEVEL_CHANGING_EVENT:

        {

            PEZoomLevelChangingEventInfo * eventInfo =

                (PEZoomLevelChangingEventInfo *) param;

            ASSERT(eventInfo != 0 && eventInfo->StructSize ==

                PE_SIZEOF_ZOOM_LEVEL_CHANGING_EVENT_INFO);
            // TODO
        }

            break;
        case PE_GROUP_TREE_BUTTON_CLICKED_EVENT:

        {

            PEGroupTreeButtonClickedEventInfo * eventInfo =

                (PEGroupTreeButtonClickedEventInfo *)param;

            ASSERT(eventInfo != 0 && eventInfo->StructSize ==

                 PE_SIZEOF_GROUP_TREE_BUTTON_CLICKED_EVENT_INFO);
            // TODO
        }

            break;
        case PE_CLOSE_BUTTON_CLICKED_EVENT:

        {

            PECloseButtonClickedEventInfo *eventInfo =

                (PECloseButtonClickedEventInfo *)param;

            ASSERT(eventInfo != 0 && eventInfo->StructSize ==

                PE_SIZEOF_CLOSE_BUTTON_CLICKED_EVENT_INFO);
            // TODO
        }

            break;
        case PE_SEARCH_BUTTON_CLICKED_EVENT:

        {

            PESearchButtonClickedEventInfo *eventInfo =

                (PESearchButtonClickedEventInfo *)param;

            ASSERT(eventInfo != 0 && eventInfo->StructSize ==

                PE_SIZEOF_SEARCH_BUTTON_CLICKED_EVENT_INFO);
            // TODO
        }

            break;
        case PE_SHOW_GROUP_EVENT:

        {

            PEShowGroupEventInfo * eventInfo =

                (PEShowGroupEventInfo *)param;

            ASSERT(eventInfo != 0 && eventInfo->StructSize ==

                PE_SIZEOF_SHOW_GROUP_EVENT_INFO);
            // TODO
        }

            break;
        case PE_DRILL_ON_GROUP_EVENT:

        {

            PEDrillOnGroupEventInfo * eventInfo =

                (PEDrillOnGroupEventInfo *) param;

            ASSERT(eventInfo != 0 && eventInfo->StructSize ==

                PE_SIZEOF_DRILL_ON_GROUP_EVENT_INFO);
            // TODO
        }

            break;
        case PE_DRILL_ON_DETAIL_EVENT:

        {

            PEDrillOnDetailEventInfo * eventInfo =

                (PEDrillOnDetailEventInfo *) param;

            ASSERT(eventInfo != 0 && eventInfo->StructSize ==

                PE_SIZEOF_DRILL_ON_DETAIL_EVENT_INFO);
            // TODO
        }

            break;
        case PE_READING_RECORDS_EVENT:

        {

            PEReadingRecordsEventInfo * readingRecordsInfo =

                (PEReadingRecordsEventInfo *) param;

            ASSERT(readingRecordsInfo != 0 &&

                readingRecordsInfo->StructSize ==

                PE_SIZEOF_READING_RECORDS_EVENT_INFO);
            // TODO
        }

            break;
        case PE_START_EVENT:

        {

            PEStartEventInfo * startEventInfo =

                (PEStartEventInfo *) param;

            ASSERT(startEventInfo != 0 &&

                startEventInfo->StructSize ==

                PE_SIZEOF_START_EVENT_INFO);
            // TODO
        }

            break;
        case PE_STOP_EVENT:

        {

            PEStopEventInfo * stopEventInfo =

                (PEStopEventInfo *) param;

            ASSERT(stopEventInfo != 0 &&

                stopEventInfo->StructSize ==

                PE_SIZEOF_STOP_EVENT_INFO);
            // TODO
        }

            break;
        default:

            break;
    }
    return TRUE;

}
// call this function after open a print job

// before call PEStartPrintJob
BOOL initializeEvent(short printJob)

{

    // initialize window options

    // do not have to set window options to get events,

    // however, some of the events are fired only when

    // certain window options are on.
    PEWindowOptions windowOptions;

    windowOptions.StructSize = PE_SIZEOF_WINDOW_OPTIONS;
    PEGetWindowOptions(printJob, &windowOptions);
    windowOptions.hasGroupTree = TRUE;

    windowOptions.hasSearchButton = TRUE;

    windowOptions.canDrillDown = TRUE;
    if(!PESetWindowOptions(printJob, &windowOptions))

        return FALSE;
    // enable event.

    // by default, events are disabled.
    PEEnableEventInfo eventInfo;

    eventInfo.StructSize = sizeof(PEEnableEventInfo);

    eventInfo.activatePrintWindowEvent = PE_UNCHANGED;

    eventInfo.closePrintWindowEvent = TRUE;

    eventInfo.startStopEvent = TRUE;

    eventInfo.printWindowButtonEvent = PE_UNCHANGED;

    eventInfo.drillEvent = TRUE;

    eventInfo.readingRecordEvent = TRUE;
    if(!PEEnableEvent(printJob, &eventInfo))

        return FALSE;
    // set tracking cursor, gives the user feedback

    // when the cursor is in the detail area

    // (for a drill-down on detail event)

    // use the default cursor behavior in group area.
    PETrackCursorInfo cursorInfo;

    cursorInfo.StructSize = sizeof(PETrackCursorInfo);

    cursorInfo.groupAreaCursor = PE_UNCHANGED;

    cursorInfo.groupAreaFieldCursor = PE_UNCHANGED;

    cursorInfo.detailAreaCursor = PE_TC_CROSS_CURSOR;

    cursorInfo.detailAreaFieldCursor = PE_TC_IBEAM_CURSOR;

    cursorInfo.graphCursor = PE_UNCHANGED;
    if(!PESetTrackCursorInfo(printJob, &cursorInfo))

        return FALSE;
    // set call back function

    if (!PESetEventCallback(printJob, lEventCallback, 0))

        return FALSE;
    return TRUE;

}


Distributing Crystal Report Engine applications

Crystal Reports comes with a royalty-free runtime license for any application that uses the Crystal Report Engine through any of the methods described in this chapter. When distributing a Crystal Report Engine application, you must also distribute several runtime files required by the Crystal Report Engine. These files are listed in the Crystal Reports Developer Runtime Help (Runtime.hlp). Be sure to carefully examine this Help file and distribute the appropriate runtime files with your application. All runtime files are included under the runtime license agreement unless otherwise stated.


Additional sources of information

If you are working with the Crystal Report Engine API in Visual Basic, refer to Enhancements to the Crystal Report Print Engine API, for information specific to Visual Basic. Delphi programmers can find information specific to using the Crystal Report Engine API with Delphi under Crystal Visual Component Library in the Techrefvol2.pdf.


Crystal Report Engine Index

The Crystal Report Engine API is a powerful development tool for your reporting needs. In this section you will find detailed information on the functions, structures and constants of the Crystal Report Engine API. Syntax for the functions and structures is provided for C, Microsoft Visual Basic, and Delphi. In addition you will find a section on obsolete functions, structures, and constants, including a list of obsolete calls with the applicable replacement calls.

Click the appropriate link to jump to that section:

  • Print Engine Functions
  • Print Engine Structures
  • Microsoft Windows Structures
  • Print Engine Constants
  • Obsolete Functions, Structures, and Constants


Print Engine Functions

The Print Engine functions are listed alphabetically in this section.

  • PEAddParameterCurrentRange
  • PEAddParameterCurrentValue
  • PEAddParameterDefaultValue
  • PECancelPrintJob
  • PECanCloseEngine
  • PECheckFormula
  • PECheckGroupSelectionFormula
  • PECheckNthTableDifferences
  • PECheckSelectionFormula
  • PECheckSQLExpression
  • PECloseEngine
  • PEClosePrintJob
  • PECloseSubreport
  • PECloseWindow
  • PEConvertPFInfotoVInfo
  • PEConvertVInfotoPFInfo
  • PEDeleteNthGroupSortField
  • PEDeleteNthParameterDefaultValue
  • PEDeleteNthSortField
  • PEDiscardSavedData
  • PEEnableNthAlert
  • PEEnableEvent
  • PEEnableProgressDialog
  • PEExportPrintWindow
  • PEExportTo
  • PEFreeDevMode
  • PEGetAllowPromptDialog
  • PEGetAreaFormat
  • PEGetAreaFormatFormula
  • PEGetEnableEventInfo
  • PEGetErrorCode
  • PEGetErrorText
  • PEGetExportOptions
  • PEGetFieldMappingType
  • PEGetFormula
  • PEGetFormulaSyntax
  • PEGetGraphAxisInfo
  • PEGetGraphFontInfo
  • PEGetGraphOptionInfo
  • PEGetGraphTextDefaultOption
  • PEGetGraphTextInfo
  • PEGetGraphTypeInfo
  • PEGetGroupCondition
  • PEGetGroupOptions
  • PEGetGroupSelectionFormula
  • PEGetHandleString
  • PEGetJobStatus
  • PEGetMargins
  • PEGetNDetailCopies
  • PEGetNFormulas
  • PEGetNGroups
  • PEGetNGroupSortFields
  • PEGetNPages
  • PEGetNParameterCurrentRanges
  • PEGetNParameterCurrentValues
  • PEGetNParameterDefaultValues
  • PEGetNParameterFields
  • PEGetNReportAlerts
  • PEGetNSections
  • PEGetNSectionsInArea
  • PEGetNSortFields
  • PEGetNSQLExpressions
  • PEGetNSubreportsInSection
  • PEGetNTables
  • PEGetNthAlertInstanceInfo
  • PEGetNthFormula
  • PEGetNthGroupSortField
  • PEGetNthParameterCurrentRange
  • PEGetNthParameterCurrentValue
  • PEGetNthParameterDefaultValue
  • PEGetNthParameterField
  • PEGetNthParameterType
  • PEGetNthParameterValueDescription
  • PEGetNthReportAlert
  • PEGetNthSQLExpression
  • PEGetNthSubreportInSection
  • PEGetNthTableLocation
  • PEGetNthTableLogOnInfo
  • PEGetNthTablePrivateInfo
  • PEGetNthTableSessionInfo
  • PEGetNthTableType
  • PEGetParameterMinMaxValue
  • PEGetParameterPickListOption
  • PEGetParameterValueInfo
  • PEGetPrintDate
  • PEGetPrintOptions
  • PEGetReportOptions
  • PEGetReportSummaryInfo
  • PEGetReportTitle
  • PEGetReportVersion
  • PEGetSectionCode
  • PEGetSectionFormat
  • PEGetSectionFormatFormula
  • PEGetSectionHeight
  • PEGetSelectedPrinter
  • PEGetSelectionFormula
  • PEGetSQLExpression
  • PEGetSQLQuery
  • PEGetSubreportInfo
  • PEGetTrackCursorInfo
  • PEGetVersion
  • PEGetWindowHandle
  • PEGetWindowOptions
  • PEHasSavedData
  • PEIsPrintJobFinished
  • PELogOffServer
  • PELogOnServer
  • PELogOnSQLServerWithPrivateInfo
  • PENextPrintWindowMagnification
  • PEOpenEngine
  • PEOpenPrintJob
  • PEOpenSubreport
  • PEOutputToPrinter
  • PEOutputToWindow
  • PEPrintControlsShowing
  • PEPrintReport
  • PEPrintWindow
  • PEReimportSubreport
  • PESelectPrinter
  • PESetAllowPromptDialog
  • PESetAreaFormat
  • PESetAreaFormatFormula
  • PESetDialogParentWindow
  • PESetEventCallback
  • PESetFieldMappingType
  • PESetFont
  • PESetFormula
  • PESetFormulaSyntax
  • PESetGraphAxisInfo
  • PESetGraphFontInfo
  • PESetGraphOptionInfo
  • PESetGraphTextDefaultOption
  • PESetGraphTextInfo
  • PESetGraphTypeInfo
  • PESetGroupCondition
  • PESetGroupOptions
  • PESetGroupSelectionFormula
  • PESetMargins
  • PESetNDetailCopies
  • PESetNthAlertConditionFormula
  • PESetNthAlertDefaultMessage
  • PESetNthAlertMessageFormula
  • PESetNthGroupSortField
  • PESetNthParameterDefaultValue
  • PESetNthParameterField
  • PESetNthParameterValueDescription
  • PESetNthSortField
  • PESetNthTableLocation
  • PESetNthTableLocation
  • PESetNthTableLogOnInfo
  • PESetNthTablePrivateInfo
  • PESetNthTableSessionInfo
  • PESetParameterMinMaxValue
  • PESetParameterPickListOption
  • PESetParameterValueInfo
  • PESetPrintDate
  • PESetPrintOptions
  • PESetReportOptions
  • PESetReportSummaryInfo
  • PESetReportTitle
  • PESetSectionFormat
  • PESetSectionFormatFormula
  • PESetSectionHeight
  • PESetSelectionFormula
  • PESetSQLExpression
  • PESetSQLQuery
  • PESetTrackCursorInfo
  • PESetWindowOptions
  • PEShow...Page
  • PEShowPrintControls
  • PEStartPrintJob
  • PETestNthTableConnectivity
  • PEVerifyDatabase
  • PEZoomPreviewWindow


PEAddParameterCurrentRange

Use PEAddParameterCurrentRange to add a parameter range to the specified parameter field of a report. Note that these parameter field capabilities are not currently supported in Web Viewers. See Working with Parameter Values and Ranges.

C Syntax
BOOL CRPE_API PEAddParameterCurrentRange (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName,

        PEValueInfo FAR *rangeStart,

        PEValueInfo FAR *rangeEnd,

        short rangeInfo );
Parameters

printJob | Specifies the print job to which you want to add a parameter current range.
parameterFieldName | Specifies a pointer to the string containing the parameter field name.
reportName | Specifies a pointer to the string containing the report name. See Remarks below.
rangeStart | Specifies a pointer to PEValueInfo, which contains the lower bound of the value range.
rangeEnd | Specifies a pointer to PEValueInfo, which contains the upper bound of the value range.
rangeInfo | Use this bitwise value to indicate whether the upper and/or lower bound(s) in the range should be added. Use one or more of the Range Info Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax
Declare Function PEAddParameterCurrentRange Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, rangeStart As PEValueInfo, _

    rangeEnd As PEValueInfo, ByVal rangeInfo As Integer ) As Integer
Delphi Syntax

procedure PEAddParameterCurrentRange (

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar;

    var rangeStart: PEValueInfo;

    var rangeEnd: PEValueInfo;

    rangeInfo: smallint;

    ): BOOL stdcall;


PEAddParameterCurrentValue

Use PEAddParameterCurrentValue to add a value to the specified parameter field of a report. Note that these parameter field capabilities are not currently supported in Web Viewers. See Working with Parameter Values and Ranges.

C Syntax
BOOL CRPE_API PEAddParameterCurrentValue (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName,

        PEValueInfo FAR *currentValue );
Parameters

printJob | Specifies the print job to which you want to add a parameter current value.
parameterFieldName | Specifies a pointer to the string containing the parameter field name.
reportName | Specifies a pointer to the string containing the report name. See Remarks below.
currentValue | Specifies a pointer to PEValueInfo, which will contain the value to be added to the parameter field. Use PE_VI_NOVALUE to indicate no value when not NULL (for example, PEValueInfo.currentValue = PE_VI_NOVALUE).

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.

This call will succeed when called with a ranged parameter. It will add a range with the start and end points equal to the given value to the Current Range list (if there are multiple ranges, otherwise it will replace the current range).

VB Syntax
Declare Function PEAddParameterCurrentValue Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, currentValue As PEValueInfo ) As Integer
Delphi Syntax
procedure PEAddParameterCurrentValue (

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar;

    var currentValue: PEValueInfo

    ): BOOL stdcall;


PEAddParameterDefaultValue

Use PEAddParameterDefaultValue to add a value to the group of default values for the specified parameter in a report.

C Syntax
BOOL CRPE_API PEAddParameterDefaultValue (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName,

        PEValueInfo FAR *valueInfo );
Parameters

printJob | Specifies the print job to which you want to add a parameter default value.
parameterFieldName | Specifies a pointer to the name of the parameter field to which the default value will be added.
reportName | Specifies a pointer to the report name. See Remarks below.
valueInfo | Specifies a pointer to PEValueInfo which will contain the added default value.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax
Declare Function PEAddParameterDefaultValue Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, valueInfo As PEValueInfo ) As Integer
Delphi Syntax
procedure PEAddParameterDefaultValue (

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar;

    var valueInfo: PEValueInfo

    ): BOOL stdcall;


PECancelPrintJob

Use PECancelPrintJob to cancel the printing of a report. This function can be tied to a control that allows the user to cancel a print job in progress. You can use this command as a replacement for the Cancel button when PEShowPrintControls, disables the Print Control buttons.

C Syntax
void CRPE_API PECancelPrintJob (

        short printJob );
Parameter

printJob

Specifies the print job that you want to cancel.

Returns

Void.

VB Syntax
Declare Sub PECancelPrintJob Lib "crpe32.dll" (ByVal printJob As
Integer)
Delphi Syntax
procedure PECancelPrintJob (

    printJob: Word

    )stdcall;
dBASE for Windows Syntax

EXTERN CVOID PECancelPrintJob (CWORD) CRPE.DLL


PECanCloseEngine

Use PECanCloseEngine to determine whether or not the Crystal Report Engine can be closed. Use this function before calling PECloseEngine, to verify that the engine is no longer processing print jobs. If the Crystal Report Engine closes while a print job is still running, an error can occur in your application or on the user's system.

C Syntax

BOOL CRPE_API PECanCloseEngine (void);

Returns
  • TRUE if the Engine can be closed.
  • FALSE if the Engine is busy.
VB Syntax

Declare Function PECanCloseEngine Lib "crpe32.dll" () As Integer

Delphi Syntax
function PECanCloseEngine:

    Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PECanCloseEngine () CRPE.DLL


PECheckFormula

Use to check the text of a named formula for validity. Use this function to check a named formula for errors.

C Syntax
BOOL CRPE_API PECheckFormula (

        short printJob,

        const char FAR *formulaName );
Parameters

printJob | Specifies the print job containing the named formula that you want to check.
formulaName | Specifies a pointer to the name of the formula that you want to check for errors.

Returns
  • TRUE if the formula is correct.
  • FALSE if the formula has an error.
Remarks
  • When specifying the name of the formula, do not use the @ symbol before the name. The @ symbol is only used by Crystal Reports to separate a formula field from other types of fields.
  • PECheckFormula works like the Check button that appears in the Crystal Reports Formula Editor.
VB Syntax

VB Sample Code for modifying formulas

Declare Function PECheckFormula Lib "crpe32.dll" (ByVal printJob As
Integer, ByVal FormulaName As String) As Integer
Delphi Syntax

Delphi code for getting/setting formulas

function PECheckFormula (

    printJob: Word;

    formulaName: PChar

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PECheckFormula (CWORD, CSTRING) CRPE.DLL


PECheckGroupSelectionFormula

Use PECheckGroupSelectionFormula to check the text of the report's group selection formula for errors. Use this function when the group selection formula in a report has changed and you need to check the new group selection formula.

C Syntax
BOOL CRPE_API PECheckGroupSelectionFormula (

        short printJob );
Parameter

printJob

Specifies the print job for the report containing the group selection formula that you want to check.

Returns
  • TRUE if the selection formula does not have an error.
  • FALSE if the selection formula contains an error. See Remarks below.
Remarks
  • You can use PECheckGroupSelectionFormula to provide your users with the functionality of the Check button that appears in the Crystal Reports Formula Editor.
  • If PECheckGroupSelectionFormula returns FALSE, you can provide the associated error text with calls to PEGetErrorCode; PEGetErrorText; and PEGetHandleString.
VB Syntax

VB Sample Code for modifying selection formulas and group selection formulas

Declare Function PECheckGroupSelectionFormula Lib "crpe32.dll" (ByVal
printJob As Integer) As Integer
Delphi Syntax
function PECheckGroupSelectionFormula (

    printJob: Word

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PECheckGroupSelectionFormula (CWORD) CRPE.DLL


PECheckNthTableDifferences

Use PECheckNthTableDifferences to retrieve database table differences. This function is not implemented for reports based on a dictionary.

C Syntax
BOOL CRPE_API PECheckNthTableDifferences (

        short printJob,

        short tableN,

        PETableDifferenceInfo FAR *tabledifferenceinfo );
Parameters

printJob | Specifies the print job for the report containing the database table that you want to check.
tableN | Specifies the 0-based number of the table for which you want to retrieve table location information. The first table is table 0. The last table is N-1.
tabledifferenceinfo | Specifies a pointer to PETableDifferenceInfo, which will contain the information retrieved.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
  • Returns Error Codes, PE_ERR_NOTIMPLEMENTED if the specified report was based on a dictionary.
VB Syntax
Declare Function PECheckNthTableDifferences Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal tableN As Integer,

    tabledifferenceinfo As PETableDifferenceInfo ) As Integer
Delphi Syntax
function PECheckNthTableDifferences (

  printJob                : Smallint;

  tableN                  : Smallint;

  var tabledifferenceinfo : PETableDifferenceInfo): Bool; {$ifdef WIN32}

        stdcall; {$endif}


PECheckSelectionFormula

Use PECheckSelectionFormula to check the text of the report's record selection formula for errors. Use this function whenever the record selection formula has been changed and you want to check the formula for syntax errors.

C Syntax
BOOL CRPE_API PECheckSelectionFormula (

        short printJob );
Parameter

printJob

Specifies the print job containing the record selection formula that you want to check.

Returns
  • TRUE if the selection formula does not have an error.
  • FALSE if the selection formula contains an error. See Remarks below.
Remarks
  • You can use PECheckSelectionFormula to provide your users with the functionality of the Check button that appears in the Crystal Reports Formula Editor.
  • If PECheckSelectionFormula returns FALSE, you can provide the associated error text with calls to PEGetErrorCode; PEGetErrorText; and PEGetHandleString.
VB Syntax

VB Sample Code for modifying selection formulas and group selection formulas

Declare Function PECheckSelectionFormula Lib "crpe32.dll" (ByVal
printJob As Integer) As Integer
Delphi Syntax
function PECheckSelectionFormula (

    printJob: Word

     ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PECheckSelectionFormula (CWORD) CRPE.DLL


PECheckSQLExpression

Use to check the text of the specified SQL expression for errors. Use this function whenever the SQL expression has been changed and you want to check the formula for syntax errors.

C Syntax
BOOL CRPE_API PECheckSQLExpression (

        short printJob,

        const char FAR *expressionName );
Parameters

printJob | Specifies the print job containing the SQL expression that you want to check.
expressionName | Specifies a pointer to the name of the SQL expression that you want to check.

Returns
  • TRUE if the SQL expression does not have an error.
  • FALSE if the SQL expression contains an error.
Remarks

You must be connected to the database to use this function.

VB Syntax

Declare Function PECheckSQLExpression Lib "crpe32.dll" (ByVal printJob
As Integer, ByVal expressionName As String) As Integer
Delphi Syntax

function PECheckSQLExpression (

    printJob: smallint;

    const expressionName: PChar

    ): Bool stdcall;
PEClearParameterCurrentValuesAndRanges

Use PEClearParameterCurrentValuesAndRanges to clear the specified parameter field of all current values and ranges.

C Syntax
BOOL CRPE_API PEClearParameterCurrentValuesAndRanges (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName );
Parameters

printJob | Specifies the print job for which you want to clear specified parameter fields.
parameterField Name | Specifies a pointer to the string containing the parameter field name.
reportName | Specifies a pointer to the string containing the report name. See Remarks below

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

Declare Function PEClearParameterCurrentValuesAndRanges Lib "crpe32.dll"
_

    ( ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String ) As Integer
Delphi Syntax
function PEClearParameterCurrentValuesAndRanges (

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar

    ): BOOL stdcall;


PECloseEngine

Use PECloseEngine to terminate the Crystal Report Engine. All printing is stopped and all windows are closed. This function stops the Crystal Report Engine from sending output, but the report may continue to print from data remaining in the spooler.

C Syntax
void CRPE_API PECloseEngine (void);
Returns

Void.

Remarks
  • Once this function has been called, no other Crystal Report Engine functions can be called except PEOpenEngine.
  • Call PECanCloseEngine, before calling this function to make sure no print jobs are in a
    busy state.
VB Syntax

Declare Sub PECloseEngine Lib "crpe32.dll" ()

Delphi Syntax

Delphi code for opening and closing the Print Engine

procedure PECloseEngine

    stdcall;
dBASE for Windows Syntax

EXTERN CVOID PECloseEngine () CRPE.DLL


PEClosePrintJob

Use PEClosePrintJob to close the print job. If printing has not yet finished, it continues; if the preview window is open, it stays open. This function is used as a mandatory part of each Custom-Print Link to shut down the print job once it has finished printing.

C Syntax
BOOL CRPE_API PEClosePrintJob (

        short printJob );
Parameter

printJob

Specifies the print job that you want to close.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Once this function has been called, most other Crystal Report Engine functions except PEOpenPrintJob; PECloseEngine; PEGetVersion; and PELogOnServer, cannot be called.

VB Syntax
Declare Function PEClosePrintJob Lib "crpe32.dll" (ByVal printJob _

        As Integer) As Integer
Delphi Syntax

Delphi code for opening and closing a PrintJob

function PEClosePrintJob (

    printJob: Word

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PEClosePrintJob (CWORD) CRPE.DLL


PECloseSubreport

Use PECloseSubreport to close the specified subreport.

C Syntax
BOOL CRPE_API PECloseSubreport (

        short printJob );
Parameter

printJob

Specifies the print job for the subreport that you want to close.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Once this function has been called, PEGetSubreportInfo, or any other Crystal Report Engine function that applies to the subreport cannot be called.

VB Syntax
Declare Function PECloseSubreport Lib "crpe32.dll" (

    ByVal printJob As Integer ) As Integer
Delphi Syntax
function PECloseSubreport (

    printJob: Word

    ): Bool stdcall;
dBASE for Windows Syntax
EXTERN CLOGICAL PECloseSubreport(CWORD) CRPE.DLL


PECloseWindow

Use PECloseWindow to close the preview window. Use this function as part of a Custom-Print Link to enable the user to review the report in the preview window and then to close the window in response to a user event. Use PECloseWindow to replace the Close button when PEShowPrintControls disables the Print Control buttons.

C Syntax
void CRPE_API PECloseWindow (

        short printJob );
Parameter

printJob

Specifies the print job for which you want to close the preview window.

Returns

Void.

Remarks

The preview window will not be closed if it is busy (generating pages, reading records, etc.).

VB Syntax

VB Sample Code for Previewing a Report

Declare Sub PECloseWindow Lib "crpe32.dll" ( ByVal printJob As Integer )

Delphi Syntax
procedure PECloseWindow (

    printJob: Word

    )stdcall;
dBASE for Windows Syntax

EXTERN CVOID PECloseWindow (CWORD) CRPE.DLL


PEConvertPFInfotoVInfo

Use PEConvertPFInfotoVInfo to convert the value returned in the CurrentValue or DefaultValue member of PEParameterFieldInfo, to the appropriate type and place the result in PEValueInfo.

C Syntax
BOOL CRPE_API PEConvertPFInfoToVInfo(

        void FAR *value,

        short valueType,

        PEValueInfo FAR *valueInfo );
Parameters

value | Specifies a pointer to the current or default parameter value (returned from PEGetNthParameterField) to convert.
valueType | Specifies the type of parameter field from which the value came. Use one of the Parameter Field Value Type Constants.
valueInfo | Specifies a pointer to PEValueInfo, that is used to store the value in converted form.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for converting to parameter field values

Declare Function PEConvertPFInfoToVInfo Lib "crpe32.dll" (ByVal value _

    As Any, ByVal valueType As Integer, valueInfo As PEValueInfo) As
Integer
Delphi Syntax

Delphi code for getting/setting parameter field information

function PEConvertPFInfoToVInfo (

    value: PChar;

    valueType: Word;

    var valueInfo: PEValueInfo

    ): Bool stdcall;


PEConvertVInfotoPFInfo

Use PEConvertVInfotoPFInfo to convert a value contained in PEValueInfo, into the binary representation expected by PESetNthParameterField.

C Syntax
BOOL CRPE_API PEConvertVInfoToPFInfo (

        PEValueInfo FAR *valueInfo,

        WORD FAR *valueType,

        void FAR *value );
Parameters

valueInfo | Specifies a pointer to PEValueInfo, that contains the value to be converted.
valueType | Specifies a pointer to the type of the value.
value | Specifies a pointer used to store the value in converted form for use in PESetNthParameterField.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for converting to parameter field values

Declare Function PEConvertVInfoToPFInfo Lib "crpe32.dll" (valueInfo _

    As PEValueInfo, ByVal valueType as Integer, ByVal value As Any) As
Integer
Delphi Syntax

Delphi code for getting/setting parameter field information

function PEConvertVInfoToPFInfo (

    var valueInfo: PEValueInfo;

    var valueType: Word;

    value: Pchar

    ): Bool stdcall;


PEDeleteNthGroupSortField

Use PEDeleteNthGroupSortField to remove the specified group sort field from the sort order. This function is used as part of a Custom-Print Link whenever you want to delete group sort fields that were established for the report at design time. When you give the user the ability to delete group sort field(s) at print time, your link must include code to replace sortFieldN with user-generated values.

This function can be used by itself to delete an existing group sort field when the sort field number is already known or as one of a series of functions (PEGetNGroupSortFields called once; PEGetNthGroupSortField and PEGetHandleString called together as many times as needed to identify the correct sort field; and PEDeleteNthGroupSortField called once, when the correct sort field is identified). The series can be used in a Custom-Print Link to identify and then delete an existing group sort field and/or sort order in response to a user selection at print time.

C Syntax
BOOL CRPE_API PEDeleteNthGroupSortField (

        short printJob,

        short sortFieldN );
Parameters

printJob | Specifies the print job from which you want to delete a group sort field.
sortFieldN | Specifies the 0-based number of the sort field that you want to delete. The first group sort field is field 0. If N = 0, the function will delete the first group sort field. If the report has N group sort fields, the function can be called with sortFieldN between 0 and N-1.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

This function should be called before PEStartPrintJob or the results may be inconsistent or unexpected.

VB Syntax
Declare Function PEDeleteNthGroupSortField Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal SortFieldN As Integer ) As Integer
Delphi Syntax
function PEDeleteNthGroupSortField (

    printJob: Word;

    sortFieldN: integer

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PEDeleteNthGroupSortField (CWORD, CWORD) CRPE.DLL


PEDeleteNthParameterDefaultValue

Use to remove a default parameter value for the specified parameter in a report.

C Syntax
BOOL CRPE_API PEDeleteNthParameterDefaultValue (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName,

        short index );
Parameters

printJob | Specifies the print job from which you want to delete a default value.
parameterFieldName | Specifies a pointer to the string containing the parameter field name.
reportName | Specifies a pointer to a string containing the report name. See Remarks below.
index | Specifies the index number of the default value to be deleted.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax

Declare Function PEDeleteNthParameterDefaultValue Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, ByVal index As Integer ) As Integer
Delphi Syntax
function PEDeleteNthParameterDefaultValue (

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar;

    index: smallint

    ): BOOL stdcall;


PEDeleteNthSortField

Use PEDeleteNthSortField to remove the specified sort field from the sort order. This function is used as part of a Custom-Print Link whenever you want to delete sort fields that were established for the report at design time. When you give the user the ability to delete sort field(s) at print time, your link must include code to replace sortFieldN with user-generated values.

This function can be used by itself to delete an existing sort field when the sort field number is already known or as one of a series of functions (PEGetNSortFields, called once; var reportAlertInfo : PEReportAlertInfo) : boolean stdcall; and PEGetHandleString called together as many times as needed to identify the correct sort field; and PEDeleteNthSortField called once, when the correct sort field is identified). The series can be used in a Custom-Print Link to identify and then delete an existing sort field and/or sort order in response to a user selection at print time.

C Syntax
BOOL CRPE_API PEDeleteNthSortField (

        short printJob,

        short sortFieldN );
Parameters

printJob | Specifies the print job from which you want to delete a sort field.
sortFieldN | Specifies the 0-based number of the sort field you want to delete. The first sort field is field 0. If N = 0, the function will delete the first sort field, If the report has N sort fields, you can call the function with sortFieldN between 0 and N-1.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

This function should be called before PEStartPrintJob, or the results may be inconsistent or unexpected.

VB Syntax
Declare Function PEDeleteNthSortField Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal SortFieldN As Integer ) As Integer
Delphi Syntax
function PEDeleteNthSortField (

    printJob: Word;

    sortFieldN: integer

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PEDeleteNthSortField (CWORD, CWORD) CRPE.DLL


PEDiscardSavedData

Use PEDiscardSavedData to discard the data that was previously saved with the report. If a report has been saved with data, you can use this function to discard the saved data, forcing the Crystal Report Engine to retrieve new data the next time the report is printed.

C Syntax
BOOL CRPE_API PEDiscardSavedData (

        short printJob );
Parameter

printJob

Specifies the print job for which you want to discard the saved data.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

This function should be called before PEStartPrintJob, or the results may be inconsistent or unexpected.

VB Syntax

VB Sample Code for Custom Print Link

Declare Function PEDiscardSavedData Lib "crpe32.dll" (

    ByVal printJob As Integer ) As Integer
Delphi Syntax

Delphi code for getting/setting print options

function PEDiscardSavedData (

    printJob: Word

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PEDiscardSavedData (CWORD) CRPE.DLL


PEEnableNthAlert

Use PEEnableNthAlert to enable or disable a Report Alert.

C Syntax
BOOL CRPE_API PEEnableNthAlert (short printJob,
                                short alertN,
                                BOOL enabled);
Parameters

printJob | Specifies the print job for which you want to enable or disable Report Alerts.
alertN | Specifies the Report Alert to enable.
enabled | Specifies wether or not to enable the Report Alert. Set to TRUE to enable, or set to FALSE to disable.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEEnableNthAlert Lib "crpe32.dll" (ByVal printJob%,
ByVal alertN%, enabled As Integer) As Integer
Delphi Syntax
function PEEnableNthAlert(
   printJob : Smallint;
   alertN : Smallint;
   enabled : boolean) : boolean stdcall;


PEEnableEvent

Use PEEnableEvent to enable or disable print job events. All events are disabled by default.

C Syntax
BOOL CRPE_API PEEnableEvent (

        short printJob,

        PEEnableEventInfo Far *enableEventInfo );
Parameters

printJob | Specifies the print job for which you want to enable or disable events.
enableEventInfo | Specifies a pointer to PEEnableEventInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Delphi Syntax
function PEEnableEvent (

printJob: Word;

Var enableEventInfo: PEEnableEventInfo

): Bool stdcall;


PEEnableProgressDialog

Use PEEnableProgressDialog to specify whether the Progress dialog box is enabled. The Progress dialog box displays the progress of the report when it is running (records read, records selected, etc.).

C Syntax
BOOL CRPE_API PEEnableProgressDialog (

        short printJob,

        BOOL enable );
Parameters

printJob | Specifies the print job for which you want to enable/disable the progress dialog box.
enable | Specifies whether or not the progress dialog box is enabled. If enable is set to TRUE, the progress dialog box is enabled. If it is set to FALSE, the dialog box is disabled.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

This dialog box is enabled by default.

VB Syntax

VB Sample Code for Custom Print Link

Declare Function PEEnableProgressDialog Lib "crpe32.dll" (ByVal printJob
_

        As Integer, ByVal enable As Integer) As Integer
Delphi Syntax
function PEEnableProgressDialog (

    printJob: Word;

    enable: Bool

    ): Bool stdcall;


PEExportPrintWindow

Use PEExportPrintWindow to export the report displayed in the preview window to disk file or e-mail. This function can be used in a Custom-Print Link to enable the user to preview the report in the preview window, and then, if everything looks satisfactory, to export the report to disk file or e-mail in response to a user event. You can use PEExportPrintWindow to replace the Export button when PEShowPrintControls, disables the Print Control buttons.

C Syntax
BOOL CRPE_API PEExportPrintWindow (

        short printJob,

        BOOL toMail,

        BOOL waitUntilDone );
Parameters

printJob | Specifies the print job that you want to export to a disk file or to e-mail.
toMail | Boolean value indicates whether or not the function is to export to e-mail.
waitUntilDone | BOOL. Reserved. This parameter must always be set to TRUE.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for Previewing a Report

Declare Function PEExportPrintWindow Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal ToMail As Integer,

    ByVal WaitUntilDone As Integer ) As Integer
Delphi Syntax
function PEExportPrintWindow (

    printJob: Word;

    toMail: Bool;

    waitUntilDone: Bool

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PEExportPrintWindow (CWORD, CLOGICAL, CLOGICAL) CRPE.DLL


PEExportTo

Use PEExportTo to export a print job using the name, format, and destination specified in the PEExportOptions. Use this function any time you want to print a report to a file or export it for use in other programs.

C Syntax
BOOL CRPE_API PEExportTo (

        short printJob,

        PEExportOptions FAR *options );
Parameters

printJob | Specifies the print job that you want to export.
options | Specifies a pointer to PEExportOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for exporting a report

Declare Function PEExportTo Lib "crpe32.dll" ( ByVal printJob As
Integer,

    ExportOptions As PEExportOptions ) As Integer

Note: Visual Basic method PEExportTo will fail unless method PEGetExportOptions is called.

Delphi Syntax
function PEExportTo (

    printJob: Word;

    var options: PEExportOptions

    ): Bool stdcall;


PEFreeDevMode

Use PEFreeDevMode to return the memory associated with the specified DEVMODE Microsoft Windows structure to the heap. The DEVMODE structure must have been retrieved from PESelectPrinter, or PEGetSelectedPrinter.

C Syntax
BOOL CRPE_API PEFreeDevMode (

    short printJob,

    DEVMODEA FAR *mode );
Parameters

printJob | Specifies the print job for which you want to release the specified DEVMODE, Windows API structure.
mode | Specifies a pointer to the DEVMODE, Windows API structure that you want to release.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEFreeDevMode Lib "crpe32.dll" ( ByVal printJob As
Integer,

    mode As Any ) As Integer


PEGetAllowPromptDialog

Use PEGetAllowPromptDialog to determine whether prompting for parameter values is allowed for the specified job during printing.

C Syntax
BOOL CRPE_API PEGetAllowPromptDialog (

        short printJob );
Parameter

printJob

Specifies the print job for which you want to determine whether prompting for parameter values is allowed during printing.

Returns
  • TRUE if prompting for parameter values is allowed.
  • FALSE if prompting is not allowed.
VB Syntax
Declare Function PEGetAllowPromptDialog Lib "crpe32.dll" (ByVal printJob
_

        As Integer) As Integer
Delphi Syntax
function PEGetAllowPromptDialog (

    printJob: Smallint

    ): Bool stdcall;


PEGetAreaFormat

Use PEGetAreaFormat to retrieve the area format settings for selected areas in the specified report and supply them as member values for PESectionOptions. Use this function to update the area formats and pass them back using PESetAreaFormat.

C Syntax
BOOL CRPE_API PEGetAreaFormat (

    short printJob,

        short areaCode,

        PESectionOptions FAR *options );
Parameters

printJob | Specifies the print job from which you want to get the area format.
areaCode | Specifies the Section Codes, for the area for which you want to get format information. See Working with section codes.
options | Specifies a pointer to PESectionOptions, which will receive format information for the area.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetAreaFormat Lib "crpe32.dll" ( ByVal printJob As
Integer,

    ByVal areaCode As Integer, Options As PESectionOptions ) As Integer
Delphi Syntax
function PEGetAreaFormat (

    printJob: Word

    areaCode: integer;

    options: PESectionOptions

    ): Bool stdcall;


PEGetAreaFormatFormula

Use PEGetAreaFormatFormula to retrieve the text of a conditional area format formula as a string handle. Use this function in order to update the conditional area format formula and pass the changes back using PESetAreaFormatFormula. Use PEGetHandleString, to retrieve the formula text.

C Syntax
BOOL CRPE_API PEGetAreaFormatFormula (

        short printJob,

        short areaCode,

        short formulaName,

        HANDLE FAR *textHandle,

        short FAR *textLength );
Parameters

printJob | Specifies the print job from which you want to get the area format formula.
areaCode | Specifies the Section Codes, for the area for which you want to get format information. See Working with section codes.
formulaName | Specifies the name of the formatting formula for which you want to supply a new string. Use one of the PE_FFN_XXX Area/Section Format Formula Constants.
textHandle | Specifies a pointer to the handle of the string containing the formula text.
textLength | Specifies a pointer to the length of the formula string (in bytes) including the terminating byte.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetAreaFormatFormula Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal areaCode As Integer,

    ByVal formulaName As Integer, textHandle As Long,

    textLength As Integer ) As Integer
Delphi Syntax
function PEGetAreaFormatFormula (

    printJob: Word;

    areaCode: Word;

    formulaName: Word;

    var textHandle: HWnd;

    var textLength: Word

    ): Bool stdcall;


PEGetEnableEventInfo

Use PEGetEnableEventInfo to retrieve event enable information. Use this function to determine which events are enabled.

C Syntax
BOOL CRPE_API PEGetEnableEventInfo (

        short printJob,

        PEEnableEventInfo FAR *enableEventInfo );
Parameters

printJob | Specifies the print job for which you want to obtain information about enabled events.
enableEventInfo | Specifies a pointer to PEEnableEventInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Delphi Syntax
function PEGetEnableEventInfo(

    printJob: Word;

    Var enableEventInfo: PEEnableEventInfo

    ): Bool stdcall;


PEGetErrorCode

Use PEGetErrorCode to retrieve a number that indicates the status of the most recent Crystal Report Engine function called. When a call to another function fails, this call gets the error code that was generated so you can take some action based on that error code. PEGetErrorCode must be called immediately after the call to the function which indicated an error.

C Syntax
short CRPE_API PEGetErrorCode (

        short printJob );
Parameter

printJob

Specifies the print job from which you want to retrieve an error code. If the most recent function was called while no print job was open, use 0 for this parameter.

Returns
  • Returns the Error Codes, of the most recent error for the given job if the function was unsuccessful.
  • Returns 0 if the function completed without error.
VB Syntax

VB Sample Code for handling errors

Declare Function PEGetErrorCode Lib "crpe32.dll" (ByVal printJob As
Integer) _

        As Integer
Delphi Syntax

Delphi code for error handling

function PEGetErrorCode (

    printJob: Word

    ): Smallint stdcall;
dBASE for Windows Syntax

EXTERN CWORD PEGetErrorCode (CWORD) CRPE.DLL


PEGetErrorText

Use PEGetErrorText to return a string handle describing the status of the most recent Crystal Report Engine function called. This function is used with PEGetHandleString. These functions can be used in a Custom-Print Link to display the error string as part of an error message.

C Syntax
BOOL CRPE_API PEGetErrorText (

        short printJob,

        HANDLE FAR *textHandle,

        short Far *textLength );
Parameters

printJob | Specifies the print job from which you want to retrieve an error string. If the most recent function was called while no print job was open, use 0 this parameter.
textHandle | Specifies a pointer to the handle of the string containing the error text.
textLength | Specifies a pointer to the length of the error string (in bytes) including the terminating byte.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetErrorText Lib "crpe32.dll" (ByVal printJob As
Integer, _

        TextHandle As Long, TextLength As Integer) As Integer
Delphi Syntax

Delphi code for error handling

function PEGetErrorText (

    printJob: Word;

    var textHandle: HWnd;

    var textLength: Word

    ): Bool stdcall;


PEGetExportOptions

Use PEGetExportOptions to retrieve export options from the user before exporting the report. PEGetExportOptions can be used to present a series of dialog boxes that retrieve export options from your users. These options are used by the Crystal Report Engine to fill in PEExportOptions. Function PEExportTo, can then be used to set the print job destination using the information in PEExportOptions.

C Syntax
BOOL CRPE_API PEGetExportOptions (

        short printJob,

        PEEXportOptions FAR *options );
Parameters

printJob | Specifies the print job from which you want to get export options.
options | Specifies a pointer to PEExportOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for exporting a report

Declare Function PEGetExportOptions Lib "crpe32.dll" (

    ByVal printJob As Integer, ExportOptions As PEExportOptions ) As
Integer
Delphi Syntax
function PEGetExportOptions (

    printJob: Word;

    var options: PEExportOptions

    ): Bool stdcall;


PEGetFieldMappingType

Use PEGetFieldMappingType to retrieve the field mapping type code for the specified report.

C Syntax
BOOL CRPE_API PEGetFieldMappingType (

        short printJob,

        WORD FAR *mappingType );
Parameters

printJob | Specifies the print job from which the field mapping type code will be retrieved.
mappingType | Specifies a pointer to the appropriate PE_FM_XXX Field Mapping Type Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Unmapped report fields will be removed.
  • You need to activate the PE_MAPPING_FIELD_EVENT and define a callback function.
VB Syntax
Declare Function PEGetFieldMappingType Lib "crpe32.dll" (

    ByVal printJob As Integer, mappingType As Integer ) As Integer
Delphi Syntax
function PEGetFieldMappingType (

    printJob: smallint;

    var mappingType: Word

    ): BOOL stdcall;


PEGetFormula

Use PEGetFormula to retrieve the text of the named formula as a string handle. This function is used with PEGetHandleString. Use PESetFormula, to pass a formula back. The series can be used in a Custom-Print Link to identify and then change an existing formula in response to a user selection at print time.

C Syntax
BOOL CRPE_API PEGetFormula (

        short printJob,

        const char *formulaName,

        HANDLE FAR *textHandle,

        short FAR *textLength );
Parameters

printJob | Specifies the print job from which you want to retrieve the formula string.
formulaName | Specifies a pointer to the null-terminated string that contains the name of the formula for which you want to retrieve the formula string.
textHandle | Specifies a pointer to the handle of the string containing the formula text.
textLength | Specifies a pointer to the length of the formula string (in bytes) including the terminating byte.

Returns
  • TRUE if the call is successful.
  • FALSE if the named formula does not exist in the report.
VB Syntax

VB Sample Code for modifying formulas

Declare Function PEGetFormula Lib "crpe32.dll" (ByVal printJob As
Integer, ByVal FormulaName As String, TextHandle As Long, TextLength As
Integer) As Integer
Delphi Syntax

Delphi code for getting/setting formulas

function PEGetFormula (

    printJob: Word;

    formulaName: PChar;

    var textHandle: HWnd;

    var textLength: Word

    ): Bool stdcall;


PEGetFormulaSyntax

Use PEGetFormulaSyntax to retrieve the syntax information associated with the formula addressed in the last formula API call.

C Syntax
BOOL CRPE_API PEGetFormulaSyntax (

    short printJob,

    PEFormulaSyntax FAR *formulaSyntax );
Parameters

printJob | Specifies the print job for which you want to determine formula syntax.
formulaSyntax | Specifies a pointer to PEFormulaSyntax, which will contain the information that you want to retrieve. See Remarks below.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • If PEGetFormulaSyntax is called before any Formula API is called, then the default value returned will be PE_UNCHANGED.
  • For running total condition formula:
      • formulaSyntax[0] is the syntax for the evalFormula.
      • formulaSyntax[1] is the syntax for the reset formula.
VB Syntax
Declare Function PEGetFormulaSyntax Lib "crpe32.dll" (

    ByVal printJob As Integer, formulaSyntax As PEFormulaSyntax ) As
Integer


PEGetGraphAxisInfo

Use PEGetGraphAxisInfo to retrieve the several chart axis options that are available.

C Syntax
BOOL CRPE_API PEGetGraphAxisInfo (

        short printJob,

        short sectionN,

        short graphN,

        PEGraphAxisInfo FAR * graphAxisInfo );
Parameters

printJob | Specifies the print job from which you want to retrieve chart axis information.
sectionN | Specifies the section of the report containing the chart for which you want to retrieve chart axis information.
graphN | Specifies for which chart within the section you want to retrieve the chart axis information. This value is 0-based. Charts are numbered based on their order of insertion into the report.
graphAxisInfo | Specifies a pointer to PEGraphAxisInfo, which will contain the information retrieved.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetGraphAxisInfo Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionN As Integer,

    ByVal graphN As Integer, graphAxisInfo As PEGraphAxisInfo ) As
Integer
Delphi Syntax
function PEGetGraphAxisInfo (

  printJob          : Smallint;

  sectionN          : Smallint;

  graphN            : Smallint;

  var graphAxisInfo : PEGraphAxisInfo): Bool; {$ifdef WIN32} stdcall;
{$endif}


PEGetGraphFontInfo

Use PEGetGraphFontInfo to retrieve the font information set for the specified chart.

C Syntax
BOOL CRPE_API PEGetGraphFontInfo (

        short printJob,

        short sectionN,

        short graphN,

        WORD titleFontType,

        PEFontColorInfo FAR * fontColourInfo );
Parameters

printJob | Specifies the print job for which you want to retrieve chart font information.
sectionN | Specifies the number of the section in which the chart appears. This parameter should be within the range obtained by PEGetNSections.
graphN | Specifies for which chart within the section you want to retrieve the font information. This value is 0-based. Charts are numbered based on their order of insertion into the report.
titleFontType | Uses one of the PE_GTF_XXX Graph Text Font Constants.
fontColourInfo | Specifies a pointer to PEFontColorInfo, which will contain the information retrieved.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetGraphFontInfo Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionN As Integer,

    ByVal graphN As Integer, ByVal titleFontType As Integer,

    fontColourInfo As PEFontColorInfo ) As Integer
Delphi Syntax
function PEGetGraphFontInfo (

  printJob           : Smallint;

  sectionN           : Smallint;

  graphN             : Smallint;

  titleFontType      : Word;

  var fontColourInfo : PEFontColorInfo): Bool; {$ifdef WIN32}
stdcall;{$endif}


PEGetGraphOptionInfo

Use PEGetGraphOptionInfo to retrieve display options set for the specified chart.

C Syntax
BOOL CRPE_API PEGetGraphOptionInfo (

        short printJob,

        short sectionN,

        short graphN,

        PEGraphOptionInfo FAR * graphOptionInfo );
Parameters

printJob | Specifies the print job for which you want to retrieve chart display information.
sectionN | Specifies the number of the section in which the chart appears. This parameter should be within the range obtained by PEGetNSections.
graphN | Specifies for which chart within the Charts are numbered based on their order of insertion into the report.
graphOption Info | Specifies a pointer to PEGraphOptionInfo, which will contain the retrieved information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetGraphOptionInfo Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionN As Integer,

    ByVal graphN As Integer, graphOptionInfo As PEGraphOptionInfo ) As
Integer
Delphi Syntax
function PEGetGraphOptionInfo (

  printJob            : Smallint;

  sectionN            : Smallint;

  graphN              : Smallint;

  var graphOptionInfo : PEGraphOptionInfo): Bool;

        {$ifdef WIN32} stdcall; {$endif}


PEGetGraphTextDefaultOption

Use PEGetGraphTextDefaultOption to determine whether or not default chart titles will be displayed.

C Syntax
BOOL CRPE_API PEGetGraphTextDefaultOption (

    short printJob,

    short sectionN,

    short graphN,

    WORD titleType,

    BOOL FAR *useDefault );
Parameters

printJob | Specifies the print job for which you want to retrieve chart title default option information.
sectionN | Specifies the 0-based index number of the section in which the chart appears. This parameter should be within the range obtained by PEGetNSections.
graphN | Specifies the 0-based index number of the chart for which you want to retrieve the chart title default option information. Charts are numbered based on their order of insertion into the report.
titleType | Specifies the title type. Use one of the PE_GTT_XXX Graph Title Type Constants.
useDefault | Specifies a pointer to the Boolean value indicating whether or not to default chart title will be displayed.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetGraphTextDefaultOption Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionN As Integer,

    ByVal graphN As Integer, ByVal titleType As Integer,

    useDefault As Long ) As Integer


PEGetGraphTextInfo

Use PEGetGraphTextInfo to retrieve the title text information set for the specified chart. This function is used with PEGetHandleString.

C Syntax
BOOL CRPE_API PEGetGraphTextInfo (

        short printJob,

        short sectionN,

        short graphN,

        WORD titleType,

        HANDLE FAR *title,

        short FAR *titleLength );
Parameters

printJob | Specifies the print job for which you want to retrieve title text information.
sectionN | Specifies the number of the section in which the chart appears. This parameter should be within the range obtained by PEGetNSections.
graphN | Specifies the 0-based index number of the chart for which you want to retrieve the title text information. Charts are numbered based on their order of insertion into the report.
titleType | Specifies the title type. Use one of the PE_GTT_XXX Graph Title Type Constants.
title | Specifies a pointer to the handle of the title.
titleLength | Specifies a pointer to the length of the title.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetGraphTextInfo Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionN As Integer,

    ByVal graphN As Integer, ByVal titleType As Integer,

    title As Long, titleLength As Integer ) As Integer
Delphi Syntax
function PEGetGraphTextInfo (

  printJob        : Smallint;

  sectionN        : Smallint;

  graphN          : Smallint;

  titleType       : Word;

  var title       : Hwnd;

  var titleLength : Smallint): Bool; {$ifdef WIN32} stdcall; {$endif}


PEGetGraphTypeInfo

Use PEGetGraphTypeInfo to retrieve information about the type of the specified chart.

C Syntax
BOOL CRPE_API PEGetGraphTypeInfo (

        short printJob,

        short sectionN,

        short graphN,

        PEGraphTypeInfo FAR * graphTypeInfo );
Parameters

printJob | Specifies the print job for which you want to retrieve chart type information.
sectionN | Specifies the number of the section in which the chart appears. This parameter should be within the range obtained by PEGetNSections.
graphN | Specifies for which chart within the section you want to retrieve the type. This value is 0-based. Charts are numbered based on their order of insertion into the report.
graphTypeInfo | Specifies a pointer to PEGraphTypeInfo, which will contain the retrieved information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetGraphTypeInfo Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionN As Integer,

    ByVal graphN As Integer, graphTypeInfo As PEGraphTypeInfo ) As
Integer
Delphi Syntax
function PEGetGraphTypeInfo (

  printJob          : Smallint;

  sectionN          : Smallint;

  graphN            : Smallint;

  var graphTypeInfo : PEGraphTypeInfo): Bool; {$ifdef WIN32} stdcall;
{$endif}


PEGetGroupCondition

Use PEGetGroupCondition to determine the group condition information for a selected group section in the specified report. Use this function to retrieve the group condition for a group section and use PESetGroupCondition, to change the group condition once it is known.

C Syntax
BOOL CRPE_API PEGetGroupCondition (

        short printJob,

        short sectionCode,

        HANDLE FAR *conditionFieldHandle,

        short FAR *conditionFieldLength,

        short FAR *condition,

        short FAR *sortDirection );
Parameters

printJob | Specifies the print job that you want to query to determine the group conditions for a selected group.
sectionCode | Specifies the Section Codes, for the report section for which you want to get the group condition. See Working with section codes.
conditionFieldHandle | Specifies a pointer to the handle of the condition field for the selected group section.
conditionFieldLength | Specifies a pointer to the length of the condition field for the selected group section.
condition | Specifies a pointer to the condition setting for the selected group section. See Remarks below.
sortDirection | Specifies a pointer to the sort direction setting for the selected group section. Uses one of the PE_SF_XXX Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

The condition parameter returns a value that encodes both the condition and the type of the condition field. You need to apply a condition mask (PE_GC_CONDITIONMASK) or a type mask (PE_GC_TYPEMASK) against this value using a bitwise AND to determine the condition or type respectively. For example:

short result;
result = *condition & PE_GC_TYPEMASK;
if (result == PE_GC_TYPEDATE)

{

    //what you want it to do

}

Type can be any of the following PE_GC_TYPEXXX constants:

  • PE_GC_TYPEOTHER -- Any data type other than date or Boolean.
  • PE_GC_TYPEDATE -- Date data type.
  • PE_GC_TYPEBOOLEAN -- Boolean data type.
  • PE_GC_TYPETIME -- Time data type
VB Syntax
Declare Function PEGetGroupCondition Lib "crpe32.dll" (ByVal printJob As
Integer, ByVal sectionCode As Integer, ConditionFieldHandle As Long,
ConditionFieldLength As Integer, Condition As Integer, SortDirection As
Integer) As Integer
Delphi Syntax
function PEGetGroupCondition (

    printJob: Word;

    sectionCode: integer;

    var conditionFieldHandle: Hwnd;

    var conditionFieldLength: Word;

    var condition: Word;

    var sortDirection: Word

    ): Bool stdcall;


PEGetGroupOptions

Use PEGetGroupOptions to retrieve the current settings for specified groups in your report.

C Syntax
BOOL CRPE_API PEGetGroupOptions (

        short printJob,

        short groupN,

        PEGroupOptions FAR *groupOptions );
Parameters

printJob | Specifies the print job for which you want to obtain information about the group options settings.
groupN | Specifies the 0-based group number.
groupOptions | Specifies a pointer to PEGroupOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

This function gets all the information retrieved with PEGetGroupCondition, plus additional group options such as repeat group header, keep group together, and top/bottom n group sorting.

VB Syntax
Declare Function PEGetGroupOptions Lib "crpe32.dll" (ByVal printJob As
Integer, ByVal groupN As Integer, groupOptions As PEGroupOptions) As
Integer
Delphi Syntax
function PEGetGroupOptions

    printJob: Word;

    groupN: smallint;

    var groupOptions: PEGroupOptions

    ): integer stdcall;


PEGetGroupSelectionFormula

Use PEGetGroupSelectionFormula to retrieve the string handle for the group selection formula used in the specified report. This function is used with PEGetHandleString. Use PESetGroupSelectionFormula, to pass back a formula. This series can be used in a Custom-Print Link to identify and then change an existing group selection formula in response to a user selection at print time.

C Syntax
BOOL CRPE_API PEGetGroupSelectionFormula (

        short printJob,

        HANDLE FAR *textHandle,

        short FAR *textLength );
Parameters

printJob | Specifies the print job for which you want to retrieve the group selection formula string.
textHandle | Specifies a pointer to the handle of the string containing the formula text.
textLength | Specifies a pointer to the length of the formula string (in bytes) including the terminating byte.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetGroupSelectionFormula Lib "crpe32.dll" (ByVal
printJob As Integer, TextHandle As Long, TextLength As Integer) As
Integer
Delphi Syntax
function PEGetGroupSelectionFormula (

    printJob: Word;

    var textHandle: HWnd;

    var textLength: Word

    ): Bool stdcall;


PEGetHandleString

Use PEGetHandleString to retrieve the text to which the string handle is pointing. The buffer will obtain the actual text. This function is used in conjunction with functions that return variable length strings. After your program allocates a buffer of sufficient size, this function moves the string from the string handle to the buffer.

C Syntax
BOOL CRPE_API PEGetHandleString (

        HANDLE textHandle,

        char FAR *buffer,

        short bufferLength );
Parameters

textHandle | Specifies the handle of the string containing the text of interest. This handle is obtained from a variable length string function.
buffer | Specifies a pointer to the buffer into which you want the string copied.
bufferLength | Specifies the length of the buffer in bytes, including the terminating null byte. This value should be identical to the length of the string obtained by the variable length string function.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • When you call the function that produces the string, it returns a length that includes a provision for the null byte at the end of the string. A buffer set to that length will hold the entire string including the terminating null byte.
  • PEGetHandleString will copy, at most, the number of bytes indicated by bufferLength, ensuring that the string in the buffer is NULL-terminated.
  • You can only use this call once with a given string handle because the string handle is discarded once the function is called. If you expect to use the string later, you will need to save it.
VB Syntax
Declare Function PEGetHandleString Lib "crpe32.dll" (ByVal textHandle _

   As Long,  ByVal Buffer As String, ByVal BufferLength As Integer) As
Integer
Delphi Syntax
function PEGetHandleString (

    textHandle: HWnd;

    buffer: PChar;

    bufferLength: integer

    ): Bool stdcall;


PEGetJobStatus

Use PEGetJobStatus to determine the status of a print job. You can use this function in a number of programming situations, for example:

  • to trigger error messages, such as when a print job fails (due to insufficient memory, insufficient disk space, etc.);
  • to trigger screen displays (hourglass, series of graphics, etc.) that confirm to the user that work is in progress; or
  • to find out whether a job was cancelled by the user after PEStartPrintJob, returns.
C Syntax
short CRPE_API PEGetJobStatus (

        short printJob,

        PEJobInfo FAR *jobInfo );
Parameters

printJob | Specifies the print job for which you want to determine printing status.
jobInfo | Specifies a pointer to PEJobInfo, which will contain the information this function retrieves.

Returns
  • Returns 0 if PEOpenEngine or PEOpenPrintJob has not been called successfully.
  • Otherwise, returns the Job Status Constants for the specified print job.
VB Syntax
Function PEGetJobStatus(ByVal job As Integer, info As PEJobInfo) As
Integer
' To work around the problem of 4 - byte alignment the PEGetJobStatus

' call has been re-declared here. When your application calls
PEGetJobStatus

' it is calling this function which in turn calls CRPE32.DLL.
Delphi Syntax
function PEGetJobStatus (

    printJob: Word;

    var jobInfo: PEJobInfo

    ): smallint stdcall;


PEGetMargins

Use PEGetMargins to retrieve the page margin settings for the specified report. Use this function to retrieve the report margins and PESetMargins, to set the report margins.

C Syntax
BOOL CRPE_API PEGetMargins (

        short printJob,

        short FAR *left,

        short FAR *right,

        short FAR *top,

        short FAR *bottom );
Parameters

printJob | Specifies the print job that you want to query to retrieve margin information.
left | Specifies a pointer to the value of the left margin.
right | Specifies a pointer to the value of the right margin.
top | Specifies a pointer to the value of the top margin.
bottom | Specifies a pointer to the value of the bottom margin.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetMargins Lib "crpe32.dll" ( ByVal printJob As
Integer,

    LeftMargin As Integer, RightMargin As Integer,

    TopMargin As Integer, BottomMargin As Integer ) As Integer
Delphi Syntax
function PEGetMargins (

    printJob: Word;

    var left: Word;

    var right: Word;

    var top: Word;

    var bottom: Word

    ): Bool stdcall;


PEGetNDetailCopies

Use PEGetNDetailCopies to retrieve the number of copies of each Details section in the report that are to be printed. Use this function to find out how many times each Details section of the report will be printed. To change the number of times each Details section is printed, use PESetNDetailCopies.

C Syntax
BOOL CRPE_API PEGetNDetailCopies (

        short printJob,

        short FAR *nDetailCopies );
Parameters

printJob | Specifies the print job that you want to query to determine how many times each Details section is to be printed.
nDetailCopies | Specifies a pointer to the number of copies of the Details section to be printed.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetNDetailCopies Lib "crpe32.dll" (

    ByVal printJob As Integer, nDetailCopies As Integer ) As Integer
Delphi Syntax
function PEGetNDetailCopies(

    printJob: Word;

    var nDetailCopies: integer

    ): Bool stdcall;


PEGetNFormulas

Use PEGetNFormulas to determine the number of formulas in the specified report. To retrieve the formula by number, use PEGetNthFormula.

C Syntax
short CRPE_API PEGetNFormulas (

        short printJob );
Parameter

printJob

Specifies the print job that you want to query to determine the number of formulas it contains.

Returns
  • Returns the number of formulas in the report.
  • Returns -1 if an error occurs.
VB Syntax
Declare Function PEGetNFormulas Lib "crpe32.dll" (ByVal printJob As
Integer) As Integer
Delphi Syntax
function PEGetNFormulas(

    printJob: Word

    ): Smallint stdcall;
dBASE for Windows Syntax
EXTERN CWORD PEGetNFormulas (CWORD) CRPE.DLL


PEGetNGroups

Use PEGetNGroups to determine the number of groups in the specified report.

C Syntax
short CRPE_API PEGetNGroups (

        short printJob );
Parameter

printJob

Specifies the print job that you want to query to determine the number of groups.

Returns
  • Returns the number of groups in the report.
  • Returns -1 if an error occurs.
VB Syntax

VB Sample Code for modifying group conditions

Declare Function PEGetNGroups Lib "crpe32.dll" (ByVal printJob As
Integer) As Integer
Delphi Syntax

function PEGetNGroups (

    printJob: Word

    ): smallint stdcall;
dBASE for Windows Syntax

EXTERN CWORD PEGetNGroups (CWORD) CRPE.DLL


PEGetNGroupSortFields

Use PEGetNGroupSortFields to retrieve the number of group sort fields in the specified report. This function is typically used as one of a series of functions (PEGetNGroupSortFields called once; PEGetNthGroupSortField and PEGetHandleString called as many times as needed to identify the correct group sort field; and PESetNthAlertConditionFormula called once, when the correct group sort field is identified. The series can be used in a Custom-Print Link to identify and then change an existing group sort field and/or sort order in response to a user selection at print time.

C Syntax
short CRPE_API PEGetNGroupSortFields (

        short printJob );
Parameter

printJob

Specifies the print job for which you want to determine the number of contained sort fields.

Returns
  • Returns the number of group sort fields.
  • Returns 0 if there are no group sort fields defined.
  • Returns -1 if an error occurs.
VB Syntax

VB Sample Code for sorting groups

Declare Function PEGetNGroupSortFields Lib "crpe32.dll" ( _

    ByVal printJob As Integer ) As Integer
Delphi Syntax
function PEGetNGroupSortFields (

    printJob: Word

    ): Smallint stdcall;
dBASE for Windows Syntax
EXTERN CWORD PEGetNGroupSortFields (CWORD) CRPE.DLL


PEGetNPages

Use PEGetNPages to retrieve the number of pages in the report. This information can be used to allow the user to display a specific page in a preview window using PEShowNthPage (PEShow...Page), for example.

C Syntax
short CRPE_API PEGetNPages (

        short printJob );
Parameter

printJob

Specifies the print job for which you want to determine the number of pages.

Returns
  • Returns the number of pages in the report if the call is successful.
  • Returns -1 if an error occurs
VB Syntax

VB Sample Code for Previewing a Report

Declare Function PEGetNPages Lib "crpe32.dll" (ByVal printJob As
Integer) As Integer
Delphi Syntax
function PEGetNPages (

    printJob: Word

    ): Smallint stdcall;


PEGetNParameterCurrentRanges

Use PEGetNParameterCurrentRanges to retrieve the number of value ranges currently associated with the specified parameter field in a report. See Working with Parameter Values and Ranges.

C Syntax
short CRPE_API PEGetNParameterCurrentRanges (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName );
Parameters

printJob | Specifies the print job for which you want to retrieve parameter current range information.
parameterFieldName | Specifies a pointer to the string containing the parameter field name.
reportName | Specifies a pointer to the string containing the report name. See Remarks below.

Returns
  • Returns the number of value ranges associated with the specified parameter field.
  • Returns -1 if an error occurs.
VB Syntax
Declare Function PEGetNParameterCurrentRanges Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String ) As Integer
Delphi Syntax

Delphi code for getting/setting parameter field information

procedure PEGetNParameterCurrentRanges (

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar;

    ): WORD stdcall;


PEGetNParameterCurrentValues

Use PEGetNParameterCurrentValues to determine the number of values currently stored in the specified parameter field of a report. See Working with Parameter Values and Ranges.

C Syntax
short CRPE_API PEGetNParameterCurrentValues (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName );
Parameters

printJob | Specifies the print job for which you want to determine the number of parameter current values.
parameterFieldName | Specifies a pointer to the string containing the parameter field name.
reportName | Specifies a pointer to the string containing the report name. See Remarks below.

Returns
  • Returns the number of values currently stored in the parameter field.
  • Returns -1 if an error occurs.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax
Declare Function PEGetNParameterCurrentValues Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String ) As Integer
Delphi Syntax
function PEGetNParameterCurrentValues

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar

    ): Word stdcall;


PEGetNParameterDefaultValues

Use PEGetNParameterDefaultValues to determine the number of default values associated with the specified parameter in a report.

C Syntax
short CRPE_API PEGetNParameterDefaultValues (

        short printJob

        const char FAR *parameterFieldName

        const char FAR *reportName );
Parameters

printJob | Specifies the print job for which you want to determine the number of parameter default values.
parameterField Name | Specifies a pointer to the string containing the name of the parameter field.
reportName | Specifies a pointer to the string containing the name of the report. See Remarks below.

Returns
  • Returns the number of parameter default values.
  • Returns -1 if an error occurs.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax
Declare Function PEGetNParameterDefaultValues Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String ) As Integer
Delphi Syntax
function PEGetNParameterDefaultValues (

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar

    ): Smallint stdcall;


PEGetNParameterFields

Use PEGetNParameterFields to determine the number of parameter fields used in a report, including the parameter fields in all subreports.

C Syntax
short CRPE_API PEGetNParameterFields (

        short printJob );
Parameter

printJob

Specifies the print job from which you want to retrieve a parameter field count.

Returns
  • The number of parameter fields in the report.
  • Returns -1 if an error occurs.
VB Syntax

VB Sample Code for modifying parameter fields

Declare Function PEGetNParameterFields Lib "crpe32.dll" (ByVal printJob
As Integer) As Integer
Delphi Syntax

Delphi code for getting/setting parameter field information

function PEGetNParameterFields (

    printJob: Word

    ): Smallint stdcall;


PEGetNReportAlerts

Use PEGetNReportAlerts to get the number of Report Alerts in the report associated with the job handle.

C Syntax
short CRPE_API PEGetNReportAlerts (short printJob);
Parameters

printJob

Specifies the print job from which you want to get the number of Report Alerts.

Returns
  • The number of Report Alerts if the call is successful.
  • -1 if the call fails.
VB Syntax
Declare Function PEGetNReportAlerts Lib "crpe32.dll" (

    ByVal printJob As Integer) As Integer
Delphi Syntax
ffunction PEGetNReportAlerts (printJob : Smallint) : Smallint stdcall;


PEGetNSections

Use PEGetNSections to retrieve the number of sections in the specified report. By default, each report has five areas, each containing one section (Report Header, Page Header, Details, Report Footer, and Page Footer). Thus, if this function were applied to a default report, five (5) would be returned. As you add groups to your report or you add sections to one or more areas, the number of sections in the report increases.

C Syntax
short CRPE_API PEGetNSections (

        short printJob );
Parameter

printJob

Specifies the print job from which you want to get a section count.

Returns
  • Returns the number of sections in the report.
  • Returns -1 if an error occurs.
VB Syntax

VB Sample Code for modifying sections and lines

Declare Function PEGetNSections Lib "crpe32.dll" (

    ByVal printJob As Integer ) As Integer
Delphi Syntax

Delphi code for getting/setting section format

function PEGetNSections (

    printJob: Word

    ): Smallint stdcall;


PEGetNSectionsInArea

Use PEGetNSectionsInArea to retrieve the number of sections contained in the specified area of the specified report.

C Syntax
short CRPE_API PEGetNSectionsInArea (

        short printJob,

        short areaCode );
Parameters

printJob | Specifies the print job for which you want to determine the number of sections in the specified area.
areaCode | Specifies the area for which you want to retrieve the section count.

Returns
  • Returns the number of sections in the specified area of the specified report if the call is successful.
  • Returns -1 if the call fails.
VB Syntax
Declare Function PEGetNSectionsInArea Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal areaCode As Integer ) As Integer


PEGetNSortFields

Use PEGetNSortFields to retrieve the number of sort fields in the specified report. This function is typically used as one of a series of functions (PEGetNSortFields called once; var reportAlertInfo : PEReportAlertInfo) : boolean stdcall; and PEGetHandleString called together as many times as needed to identify the correct sort field; and PESetNthSortField called once when the correct sort field is identified). The series can be used in a Custom-Print Link to identify and then change an existing sort field and/or sort order in response to a user selection at print time.

C Syntax
short CRPE_API PEGetNSortFields (

        short printJob );
Parameter

printJob

Specifies the print job for which you want to determine the number of sort fields contained.

Returns
  • Returns the number of sort fields.
  • Returns 0 if there are no sort fields defined.
  • Returns -1 if an error occurs.
VB Syntax

VB Sample Code for sorting records

Declare Function PEGetNSortFields Lib "crpe32.dll" ( _

    ByVal printJob As Integer ) As Integer
Delphi Syntax
function PEGetNSortFields (

    printJob: Word

    ): smallint stdcall;
dBASE for Windows Syntax

EXTERN CWORD PEGetNSortFields (CWORD) CRPE.DLL


PEGetNSQLExpressions

Use PEGetNSQLExpressions to retrieve the number of SQL expressions in the specified report.

C Syntax
short CRPE_API PEGetNSQLExpressions (

        short printJob );
Parameter

print job

Specifies the print job for which you want to determine the number of SQL expressions.

Returns
  • Returns the number of SQL expressions in the report.
  • Returns -1 if an error occurs.
VB Syntax
Declare Function PEGetNSQLExpressions Lib "crpe32.dll" (ByVal printJob
As Integer) As Integer
Delphi Syntax
function PEGetNSQLExpressions (

    printJob: smallint

    ): smallint stdcall;


PEGetNSubreportsInSection

Use PEGetNSubreportsInSection to determines the number of subreports in the specified section.

C Syntax
short CRPE_API PEGetNSubreportsInSection (

        short printJob,

        short sectionCode );
Parameters

print job | Specifies the primary report from which you want to retrieve information about the number of subreports in a section.
sectionCode | Specifies the Section Codes, of the section for which you want a subreport count. See Working with section codes.

Returns
  • Returns the number of subreports in the specified section.
  • Returns -1 if an error occurs.
Remarks

sectionCode can be retrieved using PEGetSectionCode.

VB Syntax

VB Sample Code for modifying Subreports

Declare Function PEGetNSubreportsInSection Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionCode As Integer ) As Integer
Delphi Syntax

Delphi code for getting subreport information

function PEGetNSubreportsInSection (

    printJob: Word;

    sectionCode: Smallint

    ): Smallint stdcall;


PEGetNTables

Use PEGetNTables to retrieve the number of tables in the open report. It counts both PC and SQL databases. This function is one of a series of functions that enable you to retrieve and update database information in an opened report so that the report can be printed using different server, database, user, and/or table location settings.

C Syntax
short CRPE_API PEGetNTables (

        short printJob );
Parameter

printJob

Specifies the print job from which you want to retrieve a table count.

Returns
  • Returns the number of tables used in the report (1 = 1 table, 2 = 2 tables, etc.).
  • Returns -1 if an error occurs.
Remarks
  • This function can be used with all compatible PC databases (for example, Paradox, Xbase) as well as SQL databases (for example, SQL Server, Oracle, Netware).
  • PEGetNTables must be called after PEOpenPrintJob and before PEStartPrintJob.
VB Syntax

VB Sample Code for modifying database table settings

Declare Function PEGetNTables Lib "crpe32.dll" ( ByVal printJob As
Integer _

    ) As Integer
Delphi Syntax

Delphi code for getting/setting table location

function PEGetNTables (

    printJob: Word

    ): smallint stdcall;
dBASE for Windows Syntax

EXTERN CWORD PEGetNTables (CWORD) CRPE.DLL


PEGetNthAlertInstanceInfo

Use PEGetNthAlertInstanceInfo to retrieve the PEAlertInstanceInfo structure associated with the specified Report Alert instance. The PEAlertInstanceInfo structure contains information on a specified instance of a Report Alert.

C Syntax
BOOL CRPE_API PEGetNthAlertInstanceInfo (short printJob,
                                         short alertN,
                                         DWORD instanceN,
                                         PEAlertInstanceInfo FAR *
                                     alertInstanceInfo);
Parameters

printJob | Specifies the print job from which you want to get the number of Report Alerts.
alertN | Specifies the Report Alert from which you want to get the alert instance information.
instanceN | Specifies the instance of the Report Alert from which you want to get the alert instance information.
alertInstanceInfo | Specifies a pointer to PEAlertInstanceInfo

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Currently there is no function to get the number of Report Alert instances created when a report is alert is triggered. This functionality will be implemented in a future version.

In the present build only the first instance of the Report Alert is created at runtime. This limitation will be addressed in a future release.

VB Syntax
Declare Function PEGetNthAlertInstanceInfo Lib "crpe32.dll" (ByVal
printJob%, ByVal alertN%, ByVal instanceN As Long, alertInstanceInfo As
PEAlertInstanceInfo) As Integer
Delphi Syntax
function PEGetNthAlertInstanceInfo(
   printJob : Smallint;
   alertN : Smallint;
   instanceN : DWord;
   var alertInstanceInfo : PEAlertInstanceInfo) : boolean stdcall;


PEGetNthFormula

Use PEGetNthFormula to retrieve information about a specific formula in the report. Use this function to obtain the formula name and formula text of a specific formula in the report. This function can be used to retrieve the formula text to allow the user to edit the formula. You can then change the formula text with PESetFormula.

C Syntax
BOOL CRPE_API PEGetNthFormula (

        short printJob,

        short formulaN,

        HANDLE FAR *nameHandle,

        short FAR *nameLength,

        HANDLE FAR *textHandle,

        short FAR *textLength );
Parameters

printJob | Specifies the print job from which you want to gather formula information.
formulaN | Specifies the 0-based number of the formula about which you want to gather information.
nameHandle | Specifies a pointer to the handle of the string containing the formula name.
nameLength | Specifies a pointer to the length of the formula name string (in bytes) including the terminating byte.
textHandle | Specifies a pointer to the handle of the string containing the formula text.
textLength | Specifies a pointer to the length of the formula string (in bytes) including the terminating byte.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.

Edit|Formula

VB Syntax

VB Sample Code for modifying formulas

Declare Function PEGetNthFormula Lib "crpe32.dll" (ByVal printJob As
Integer, ByVal FormulaN As Integer, NameHandle As Long, NameLength As
Integer, TextHandle As Long, TextLength As Integer) As Integer
Delphi Syntax

Delphi code for getting/setting formulas

function PEGetNthFormula (

    printJob: Word;

    formulaN: integer;

    var nameHandle: Hwnd;

    var nameLength: Word;

    var textHandle: Hwnd;

    var textLength: Word

    ): Bool stdcall;


PEGetNthGroupSortField

Use PEGetNthGroupSortField to retrieve information about one of the group sort fields in the specified report. This function is used with PEGetHandleString. PEGetNthGroupSortField returns the name of the field and the direction (ascending or descending) of the sort. See Crystal Report Engine API variable length strings for additional information.

This function is typically used as one of a series of functions (PEGetNGroupSortFields) called once; PEGetNthGroupSortField and PEGetHandleString called as many times as needed to identify the correct group sort field; and PESetNthAlertConditionFormula called once when the correct sort field is identified. The series can be used in a Custom-Print Link to identify and then change an existing group sort field and/or sort order in response to a user selection at print time.

C Syntax
BOOL CRPE_API PEGetNthGroupSortField (

        short printJob,

        short sortFieldN,

        HANDLE FAR *nameHandle,

        short FAR *nameLength,

        short FAR *direction );
Parameters

printJob | Specifies the print job from which you want to gather group sort field information.
sortFieldN | Specifies the 0-based number of the group sort field that you want to retrieve. The first group sort field is field 0. If the report has N sort fields, the function can be called with sortFieldN between 0 and N-1.
nameHandle | Specifies a pointer to the handle of the string containing the sort field name.
nameLength | Specifies a pointer to the length of the field name string (in bytes) including the terminating byte.
direction | Specifies a pointer to the sort direction. Uses one of the PE_SF_XXX Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

To find out top/bottom n group sort information, use PEGetGroupOptions.

VB Syntax
Declare Function PEGetNthGroupSortField Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal SortFieldN As Integer, _

    NameHandle As Long, NameLength As Integer, Direction As Integer _

    ) As Integer
Delphi Syntax
function PEGetNthGroupSortField (

    printJob: Word;

     sortFieldN: integer;

     var nameHandle: HWnd;

     var nameLength: Word;

     var direction: Word

    ): Bool stdcall;


PEGetNthParameterCurrentRange

Use PEGetNthParameterCurrentRange to retrieve a value range from the specified parameter field in a report. Use PEGetNParameterCurrentRanges, to get the number of value ranges currently associated with the parameter field. See Working with Parameter Values and Ranges.

C Syntax
BOOL CRPE_API PEGetNthParameterCurrentRange (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName,

        short index,

        PEValueInfo FAR *rangeStart,

        PEValueInfo FAR *rangeEnd,

        short FAR *rangeInfo );
Parameters

printJob | Specifies the print job for which you want to retrieve the parameter current range.
parameterFieldName | Specifies a pointer to the string containing the parameter field name.
reportName | Specifies a pointer to the string containing the report name. See Remarks below.
index | Specifies the index number of the value range to be retrieved.
rangeStart | Specifies a pointer to PEValueInfo, in which the beginning value in the range is returned.
rangeEnd | Specifies a pointer to PEValueInfo, in which the final value in the range is returned.
rangeInfo | Use this bitwise value to indicate whether the upper and/or lower bound(s) in the range should be retrieved. Use one or more of the Range Info Constants.

Returns
  • TRUE if the call succeeds.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax
Declare Function PEGetNthParameterCurrentRange Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, ByVal index As Integer, _

    rangeStart As PEValueInfo, rangeEnd As PEValueInfo, _

    ByVal rangeInfo As Integer ) As Integer
Delphi Syntax

Delphi code for getting/setting parameter field information

procedure PEGetNthParameterCurrentRange (

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar;

    index: smallint;

    var rangeStart: PEValueInfo;

    var rangeEnd: PEValueInfo;

    rangeInfo: smallint

    ): BOOL stdcall;


PEGetNthParameterCurrentValue

Use to retrieve a value from the specified parameter field of a report. Use PEGetNParameterCurrentValues, to determine the number of values currently held in the parameter field. See Working with Parameter Values and Ranges.

C Syntax
BOOL CRPE_API PEGetNthParameterCurrentValue (

        short printJob,

        const char FAR *parameter FieldName,

        const char FAR *reportName,

        short index,

        PEValueInfo FAR *currentValue );
Parameters

printJob | Specifies the print job for which you want to determine the parameter current value.
parameterFieldName | Specifies a pointer to a string containing the parameter field name.
reportName | Specifies a pointer to a string containing the report name. See Remarks below.
index | Specifies the index number of the value to be retrieved.
currentValue | Specifies a pointer to PEValueInfo, in which the value will be returned. If it contains no value then it will be set to the constant PE_VI_NOVALUE rather than NULL.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax
Declare Function PEGetNthParameterCurrentValue Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, ByVal index As Integer, _

    currentValue As PEValueInfo ) As Integer
Delphi Syntax

Delphi code for getting/setting parameter field information

function PEGetNthParameterCurrentValue (

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar;

    index: smallint;

    var currentValue: PEValueInfo

    ): BOOL stdcall;


PEGetNthParameterDefaultValue

Use PEGetNthParameterDefaultValue to retrieve a default value for a specified parameter field in a report. Use PEGetNParameterDefaultValues, to retrieve the number of default values for the parameter field.

C Syntax
BOOL CRPE_API PEGetNthParameterDefaultValue (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName,

        short index,

        PEValueInfo FAR *valueInfo );
Parameters

printJob | Specifies the print job from which you want to gather parameter default value information.
parameterFieldName | Specifies a pointer to the string containing the parameter field name.
reportName | Specifies a pointer to the string containing the report name. See Remarks below.
index | Specifies the index number of the default value to be retrieved.
valueInfo | Specifies a pointer to PEValueInfo, containing information about requested default value.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax
Declare Function PEGetNthParameterDefaultValue Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, ByVal index As Integer, _

    valueInfo As PEValueInfo ) As Integer
Delphi Syntax

Delphi code for getting/setting parameter field information

function PEGetNthParameterDefaultValue(

    printJob: smallint;

    const parameterFieldName: PChar;

    index: smallint;

    var valueInfo: PEValueInfo

    ): BOOL stdcall;


PEGetNthParameterField

Use PEGetNthParameterField to retrieve information about one of the parameter fields in the specified report. For new development, see Remarks below. This function returns the name of the field, the data type, and information about the value set for the field. The name of the parameter field is returned as a string handle. This function is typically used as one of a series of functions (PEGetNParameterFields, (called once); PEGetNthParameterField (called as many times as needed to identify the correct parameter field); and PESetNthParameterField, (called once when the correct parameter field is identified). The series can be used in a Custom-Print Link to identify and then change an existing parameter field value in response to a user selection at print time.

C Syntax
BOOL CRPE_API PEGetNthParameterField (

        short printJob,

        short parameterN,

        PEParameterFieldInfo FAR *parameterInfo );
Parameters

printJob | Specifies the print job that contains the parameter field about which you want to retrieve information.
parameterN | Specifies the number of the parameter field about which you want to retrieve information.
parameterInfo | Specifies a pointer to PEParameterFieldInfo, which is used to store the information you retrieve. See Remarks below.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • For new development, the Default/CurrentValueSet members of PEParameterFieldInfo must be set to FALSE and the following new calls used to access default and current value lists.
      • PEGetNParameterCurrentRanges
      • PEGetNParameterCurrentValues
      • PEGetNParameterDefaultValues
      • PEGetNthParameterCurrentRange
      • PEGetNthParameterCurrentValue
      • PEGetNthParameterDefaultValue
  • The CurrentValue member of the returned structure, PEParameterFieldInfo, will be set to CRWNULL. if the parameter is NULL.
VB Syntax
Declare Function PEGetNthParameterField Lib "crpe32.dll" (ByVal printJob
As Integer, ByVal varN As Integer, varInfo As PEParameterFieldInfo) As
Integer
Delphi Syntax
function PEGetNthParameterField (

    printJob: Word;

    varN: Smallint;

    var varInfo: PEParameterFieldInfo

    ): Bool stdcall;


PEGetNthParameterType

Use PEGetNthParameterType to retrieve the type (or origin) of a specified parameter.

C Syntax
short CRPE_API PEGetNthParameterType (

        short printJob,

        short index );
Parameters

printJob | Specifies the print job from which you want to gather parameter type information.
index | Specifies the index number of the parameter field.

Returns

Returns one of the following PE_PO_XXX Constants or -1 if the index is invalid.

PE_PO_REPORT | Report.
PE_PO_STOREDPROC | Stored Procedure.
PE_PO_QUERY | Query.

VB Syntax
Declare Function PEGetNthParameterType Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal index As Integer ) As Integer
Delphi Syntax
function PEGetNthParameterType (

    printJob: smallint;

    index: smallint

    ): smallint stdcall;


PEGetNthParameterValueDescription

Use PEGetNthParameterValueDescription to retrieve the description of the value set for a parameter.

C Syntax
BOOL CRPE_API PEGetNthParameterValueDescription (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName,

        short index,

        HANDLE FAR *valueDesc,

        short FAR *valueDescLength );
Parameters

printJob | Specifies the print job from which you want to gather parameter value description information.
parameterFieldName | Specifies a pointer to the parameterFieldName for which you want to retrieve the parameter value description.
reportName | Specifies a pointer to the report name. See Remarks below.
index | Specifies the index.
valueDesc | Specifies a pointer to the handle of the value description to be retrieved.
valueDescLength | Specifies a pointer to the length of the value description.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax
Declare Function PEGetNthParameterValueDescription Lib "crpe32.dll" (_

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, ByVal index As Integer, _

    valueDesc As Long, valueDescLength As Integer ) As Integer
Delphi Syntax
function PEGetNthParameterValueDescription (

  printJob            : Smallint;

  parameterFieldName  : PChar;

  reportName          : PChar;

  index               : Smallint;

  var valueDesc       : HWnd;

  var valueDescLength : Smallint): Bool; {$ifdef WIN32} stdcall; {$endif}


PEGetNthReportAlert

Use PEGetNthReportAlert to retrieve the PEReportAlertInfo structure from the report associated with the job handle. The PEReportAlertInfo structure contains information on a specified Report Alert.

C Syntax
BOOL CRPE_API PEGetNthReportAlert (short printJob,
                                   short alertN,
                                   PEReportAlertInfo FAR *
reportAlertInfo);
Parameters

printJob | Specifies the print job from which you want to get the number of Report Alerts.
alertN | Specifies the Report Alert from which you want to get the alert instance information.
reportalertInfo | Specifies a pointer to PEAlertInstanceInfo

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetNthReportAlert Lib "crpe32.dll" (ByVal printJob%,
ByVal alertN%, reportAlertInfo As PEReportAlertInfo) As Integer
Delphi Syntax
function PEGetNthReportAlert(
   printJob : Smallint;
   alertN : Smallint;
   var reportAlertInfo : PEReportAlertInfo) : boolean stdcall;


PEGetNthSortField

Use PEGetNthSortField to return information about one of the sort fields in the specified report. This function returns the name of the field and the direction (ascending or descending) of the sort. The name of the sort field is returned as a string handle. This function is typically used as one of a series of functions (PEGetNSortFields called once; PEGetNthSortField and PEGetHandleString called together as many times as needed to identify the correct sort field; and PESetNthSortField called once when the correct sort field is identified). The series can be used in a Custom-Print Link to identify and then change an existing sort field and/or sort order in response to a user selection at print time.

C Syntax
BOOL CRPE_API PEGetNthSortField (

        short printJob,

        short sortFieldN,

        HANDLE FAR *nameHandle,

        short FAR *nameLength,

        short FAR *direction );
Parameters

printJob | Specifies the print job from which you want to retrieve sort field information.
sortFieldN | Specifies the0-based number of the sort field you want to retrieve. The first sort field is field 0. If the report has N sort fields, the function can be called with sortFieldN between 0 and N-1.
nameHandle | Specifies a pointer to the handle of the string containing the sort field name.
nameLength | Specifies a pointer to the length of the field name string (in bytes) including the terminating byte.
direction | Specifies a pointer to the sort direction. Uses one of the PE_SF_XXX Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for sorting records

Declare Function PEGetNthSortField Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal SortNumber As Integer, _

    NameHandle As Long, NameLength As Integer, Direction As Integer _

    ) As Integer
Delphi Syntax
function PEGetNthSortField (

    printJob: Word;

    sortFieldN: integer;

    var nameHandle: HWnd;

    var nameLength: Word;

    var direction: Word

    ): Bool stdcall;


PEGetNthSQLExpression

Use PEGetNthSQLExpression to retrieve one of the SQL expressions associated with a report. Use this function with PEGetHandleString. Use PEGetNSQLExpressions, to determine the number of SQL expressions in the report.

C Syntax
BOOL CRPE_API PEGetNthSQLExpression (

        short printJob,

        short expressionN,

        HANDLE FAR *nameHandle,

        short FAR *nameLength,

        HANDLE FAR *textHandle,

        short FAR *textLength );
Parameters

printJob | Specifies the print job from which you want to gather SQL expression information.
expressionN | Specifies the numeric value indicating which expression to retrieve.
nameHandle | Specifies a pointer to the handle of the string containing the expression name.
nameLength | Specifies a pointer to the length of name string.
textHandle | Specifies a pointer to the handle of the string containing the SQL expression.
textLength | Specifies a pointer to the length of the expression string.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetNthSQLExpression Lib "crpe32.dll" (ByVal printJob
As Integer, ByVal expressionN As Integer, nameHandle As Long, nameLength
As Integer, textHandle As Long, textLength As Integer) As Integer
Delphi Syntax
function PEGetNthSQLExpression (

    printJob: smallint;

    expressionN: Smallint;

    var nameHandle: Hwnd;

    var nameLength: Smallint;

    var textHandle: Hwnd;

    var textLength: Smallint

    ): Bool stdcall;


PEGetNthSubreportInSection

Use PEGetNthSubreportInSection to retrieve a handle that is required to retrieve the name of a subreport.

Syntax
DWORD CRPE_API PEGetNthSubreportInSection (

        short printJob,

        short sectionCode,

        short subreportN );
Parameters

printJob | Specifies the primary report.
sectionCode | Specifies the Section Codes, for the report section that contains the subreport. See Working with section codes.
subreportN | Specifies the number of the subreport in the specified section. subreportN is zero based. The first report in the section will be 0, the second will be 1, etc. If there are no subreports in the section, the function will return 0.

Returns

Returns a handle that is used to retrieve the name of the specified subreport.

Remarks

Use PEGetSubreportInfo, to retrieve information about the subreport by passing the subreport handle returned by PEGetNthSubreportInSection.

VB Syntax
Declare Function PEGetNthSubreportInSection Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionCode As Integer,

    ByVal subreportN As Integer ) As Long
Delphi Syntax
function PEGetNthSubreportInSection (

    printJob: Word;

    sectionCode: Smallint;

    subreportN: Smallint

    ): DWORD stdcall;
See Also:

Working with subreports


PEGetNthTableLocation

Use PEGetNthTableLocation to determine the location of a selected table used in the specified print job. This function is typically combined with PESetNthTableLocation to identify the location of a table and then to change it.

C Syntax
BOOL CRPE_API PEGetNthTableLocation (

        short printJob,

        short tableN,

        PETableLocation FAR *location );
Parameters

printJob | Specifies the print job from which you want to retrieve information about a table's location.
tableN | Specifies the 0-based number of the table for which you want to retrieve table location information. The first table is table 0. The last table is N-1.
location | Specifies the pointer to PETableLocation. The format of the string will be depend on the type of database specified.

Returns
  • TRUE if the call is successful0.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for modifying database table settings

Declare Function PEGetNthTableLocation Lib "crpe32.dll" ( ByVal printJob
As Integer, ByVal TableN As Integer, Location As PETableLocation ) As
Integer
Delphi Syntax

Delphi code for getting/setting table location

function PEGetNthTableLocation(

    printJob: Word;

    tableN: integer;

    var location: PETableLocation

    ): Bool stdcall;


PEGetNthTableLogOnInfo

Use PEGetNthTableLogOnInfo to retrieve log on information required by a report.

C Syntax
BOOL CRPE_API PEGetNthTableLogOnInfo (

        short printJob,

        short tableN,

        PELogOnInfo FAR *logOnInfo );
Parameters

printJob | Specifies the print job for which you want to get table log on information.
tableN | Specifies the 0-based number of the table for which you want to retrieve table log on information. The first table is table 0. The last table is N-1.
logOnInfo | Specifies the pointer to PELogOnInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • This function must be called after PEOpenPrintJob (so you have the job handle), and before PEStartPrintJob (which needs the password set to print the report).
  • The password in PELogOnInfo will always be an empty string when using this function.
VB Syntax
Declare Function PEGetNthTableLogOnInfo Lib "crpe32.dll" ( ByVal
printJob As Integer, ByVal TableN As Integer, LogOnInfo As PELogOnInfo )
As Integer
Delphi Syntax
function PEGetNthTableLogOnInfo (

    printJob: Word;

    tableN: integer;

    var logOnInfo: PELogOnInfo

    ): Bool stdcall;


PEGetNthTablePrivateInfo

Retrieves information for using data objects such as ADO, RDO, or CDO with the Active Data Driver (PS2MON.DLL).

C Syntax
BOOL CRPE_API PEGetNthTablePrivateInfo (

        short printJob,

        short tableN,

        PETablePrivateInfo FAR *privateInfo );
Parameters

printJob | Identifies the print job which uses the table for which you want to retrieve the session information.
tableN | Specifies the 0-based number of the table for which you want to retrieve table private information. The first table is table 0. The last table is N-1.
privateInfo | Specifies the pointer to PETablePrivateInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Delphi Syntax
       function PESetNthTablePrivateInfo (

               printJob: Smallint;

               tableN:   Smallint;

               var privateInfo:         PETablePrivateInfo

       )   :Bool; {$ifdef WIN32} stdcall; {$endif}


PEGetNthTableSessionInfo

Use PEGetNthTableSessionInfo to set the session information for a Microsoft Access table being used in your report. Many MS Access database tables require that a session be opened before the information in the table can be used. Use PEGetNthTableSessionInfo to obtain the session information (User ID, Password, and Session Handle) for a particular table.

C Syntax
BOOL CRPE_API PEGetNthTableSessionInfo (

        short printJob,

        short tableN,

        PESessionInfo FAR *sessionInfo );
Parameters

printJob | Identifies the print job that uses the table for which you want to retrieve the session information.
tableN | Specifies the 0-based number of the table for which you want to retrieve session information. The first table is table 0. The last table is N-1.
sessionInfo | Specifies a pointer to PESessionInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • This function is only applicable for MS Access databases which require a session to be opened before the database is accessed.
  • The password in PESessionInfo will always be an empty string when using this function.
VB Syntax
Declare Function PEGetNthTableSessionInfo Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal TableN As Integer, _

    SessionInfo As PESessionInfo ) As Integer
Delphi Syntax
function PEGetNthTableSessionInfo (

    printJob: Word;

    tableN: Integer;

    var sessionInfo: PESessionInfo

    ): Bool stdcall;


PEGetNthTableType

Use PEGetNthTableType to determine the type of each table. This function is one of a series of functions that enable you to retrieve and update database information in an opened report so that the report can be printed using different server, database, user, and/or table location settings.

Syntax
BOOL CRPE_API PEGetNthTableType (

        short printJob,

        short tableN,

        PETableType FAR *tableType );
Parameters

printJob | Specifies the print job for which you want to determine a table type.
tableN | Specifies the 0-based number of the table for which you want to determine the type. Table numbers start at 0. For example, if PEGetNTables returns 2, call PEGetNthTableType twice with table numbers of 0 and 1.
tableType | Specifies a pointer to PETableType.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • The application can test DBType in PETableType or test the database DLL name used to create the report. DBType is the structure returned by PEGetNthTableType.
      • DLL names have the following naming convention:

        PDB*.DLL for standard (non-SQL) databases.

        PDS*.DLL for SQL/ODBC databases.

      • In the case of ODBC (PDSODBC.DLL) the DescriptiveName includes the ODBC data source name.
  • PEGetNthTableType must be called after PEOpenPrintJob and before PEStartPrintJob.
VB Syntax

VB Sample Code for modifying database table settings

Declare Function PEGetNthTableType Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal TableN As Integer, _

    TableType As PETableType ) As Integer
Delphi Syntax

Delphi code for getting/setting table location

function PEGetNthTableType (

    printJob: Word;

    tableN: Integer;

    var tableType: PETableType

    ): Bool stdcall;


PEGetParameterMinMaxValue

Use PEGetParameterMinMaxValue to retrieve the minimum and/or maximum possible values for a specified parameter in a report.

C Syntax
BOOL CRPE_API PEGetParameterMinMaxValue (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName,

        PEValueInfo FAR *valueMin,

        PEValueInfo FAR *valueMax );
Parameters

printJob | Specifies the print job for which you want to retrieve the parameter min/max values.
parameterFieldName | Specifies a pointer to the string containing the parameter name.
reportName | Specifies a pointer to the string containing the report name. See Remarks below.
valueMin | Specifies a pointer to PEValueInfo, in which information about the minimum parameter value will be returned. See Remarks below.
valueMax | Specifies a pointer to PEValueInfo, in which information about the maximum parameter value will be returned. See Remarks below.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Regarding parameter reportName:
      • For the main report, pass an empty string ("").
      • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
  • Regarding parameters valueMin and valueMax:
      • Set valueMin to NULL to retrieve maximum value only; must be non-NULL if valueMax is NULL.
      • Set valueMax to NULL to retrieve minimum value only; must be non-NULL if valueMin is NULL.
VB Syntax
Declare Function PEGetParameterMinMaxValue Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, valueMin As PEValueInfo, _

    valueMax As PEValueInfo ) As Integer
Delphi Syntax

Delphi code for getting/setting parameter field information

function PEGetParameterMinMaxValue (

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar;

    var valueMin: PEValueInfo;

    var valueMax: PEValueInfo     }

    ): BOOL stdcall;


PEGetParameterPickListOption

Use PEGetParameterPickListOption to retrieve the parameter pick list options set for a report. This function retrieves the values in PEParameterPickListOption.

C Syntax
BOOL CRPE_API PEGetParameterPickListOption (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName,

        PEParameterPickListOption FAR *pickListOption );
Parameters

printJob | Specifies the print job from which you want to retrieve the parameter pick list options.
parameterFieldName | Specifies a pointer to the parameterFieldName for which you want to retrieve pick list options.
reportName | Specifies a pointer to the report name. See Remarks below.
pickListOption | Specifies a pointer to PEParameterPickListOption, which will contain the information retrieved.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated stringand name of the subreport as a NULL-terminated string.
VB Syntax
Declare Function PEGetParameterPickListOption Lib "crpe32.dll" (_

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, pickListOption As
PEParameterPickListOption _

    ) As Integer
Delphi Syntax
function PEGetParameterPickListOption (

  printJob           : Smallint;

  parameterFieldName : PChar;

  reportName         : PChar;

  var pickListOption : PEParameterPickListOption): Bool; {$ifdef WIN32}

        stdcall; {$endif}


PEGetParameterValueInfo

Use PEGetParameterValueInfo to retrieve the PEParameterValueInfo, structure associated with the specified parameter field in a report. This structure contains information (for example, editing possible, nullable field, multiple values, etc.) about the values which can be stored in this field. See Working with Parameter Values and Ranges.

C Syntax
BOOL CRPE_API PEGetParameterValueInfo (

        short printJob,

        const char FAR *paramterFieldName,

        const char FAR *reportName,

        PEParameterValueInfo FAR *valueInfo );
Parameters

printJob | Specifies the print job from which you want to gather parameter value information.
parameterField Name | Specifies a pointer to the string containing the parameter field name.
reportName | Specifies a pointer to the string containing the report name. See Remarks below.
valueInfo | Specifies a pointer to PEParameterValueInfo, in which the parameter value information will be returned. See Working with Parameter Values and Ranges.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax
Declare Function PEGetParameterValueInfo Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, valueInfo As PEParameterValueInfo ) As
Integer
Delphi Syntax

Delphi code for getting/setting parameter field information

function PEGetParameterValueInfo (

    printJob : smallint;

    const parameterFieldName : PChar;

    const reportNam : PChar;

    var valueInfo : PEParameterValueInfo

    ): BOOL stdcall;


PEGetPrintDate

Use PEGetPrintDate to determine the print date (if any) that was specified with the report. Use this function to retrieve the print date and pass it back using PESetPrintDate.

C Syntax
BOOL CRPE_API PEGetPrintDate (

        short printJob,

        short FAR *year,

        short FAR *month,

        short FAR *day );
Parameters

printJob | Specifies the print job for which you want to retrieve the print date setting.
year | Specifies a pointer to the year component of the print date.
month | Specifies a pointer to the month component of the print date.
day | Specifies a pointer to the day component of the print date.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

You change the print date, typically, when you want to run the report today yet have it appear to have been run on a different date. An example would be, if you were out of town on the last day of the previous month and you later want to run a report for that month and make it appear as if it were run on the last day of the month rather than the current date.

VB Syntax
Declare Function PEGetPrintDate Lib "crpe32.dll" (ByVal printJob As
Integer, Date_Year As Integer, Date_Month As Integer, Date_Day As
Integer) As Integer
Delphi Syntax
function PEGetPrintDate (

    printJob: Word;

    var year: Word;

    var month: Word;

    var day: Word

    ): Bool stdcall;


PEGetPrintOptions

Use PEGetPrintOptions to retrieve the print options specified for the report (the options that are set in the Print common dialog box) and use them to fill in PEPrintOptions. Use this function to retrieve print options from the report in order to update them and pass back using PESetPrintOptions.

C Syntax
BOOL CRPE_API PEGetPrintOptions (

        short printJob,

        PEPrintOptions FAR *options );
Parameters

printJob | Specifies the print job that you want to query to determine which print options have been set using the Print common dialog box.
options | Specifies a pointer to PEPrintOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for modifying title, options, margins, and date

Declare Function PEGetPrintOptions Lib "crpe32.dll" (

    ByVal printJob As Integer, Options As PEPrintOptions ) As Integer
Delphi Syntax

Delphi code for getting/setting print options

function PEGetPrintOptions (

    printJob: Word;

    var options: PEPrintOptions

    ): Bool stdcall;


PEGetReportOptions

Use PEGetReportOptions to retrieve the report options associated with a specified print job.

C Syntax
BOOL CRPE_API PEGetReportOptions (

        short printJob,

        PEReportOptions FAR *reportOptions );
Parameters

printJob | Specifies the print job for which you want to determine report options.
reportOptions | Specifies a pointer to PEReportAlertInfo, which contains report options for the specified print job.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetReportOptions Lib "crpe32.dll" (ByVal printJob _

        As Integer, reportOptions As PEReportOptions) As Integer
Delphi Syntax
function PEGetReportOptions (

    printJob: smallint;

    var reportOptions: PEReportOptions

    ): Bool stdcall;


PEGetReportSummaryInfo

Use PEGetReportSummaryInfo to retrieve summary information about the report (for example, report title, author, and comments).

C Syntax
BOOL CRPE_API PEGetReportSummaryInfo (
 short printJob,
 PEReportSummaryInfo FAR *summaryInfo);
Parameters

printJob | Specifies the print job for which you want to get the report summary information.
summaryInfo | Specifies a pointer to PEReportSummaryInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetReportSummaryInfo Lib "crpe32.dll" (

    ByVal printJob As Integer, summaryInfo As PEReportSummaryInfo ) As
Integer
Delphi Syntax
function PEGetReportSummaryInfo (

    printJob: integer;

    var summaryInfo: PEReportSummaryInfo

    ): Bool stdcall;


PEGetReportTitle

Use PEGetReportTitle to retrieve the handle of the report title string in the report summary information. If the job is a subreport, it returns the handle of the subreport name. Use this function with PEGetHandleString. Use PESetReportTitle, to pass back a report title. The series can be used in Custom-Print Links to identify and change an existing report title in response to a user selection at print time.

C Syntax
BOOL CRPE_API PEGetReportTitle (

        short printJob,

        HANDLE FAR *titleHandle,

        short FAR *titleLength );
Parameters

printJob | Specifies the print job for which you want to get the report title.
titleHandle | Specifies a pointer to the handle of the title string.
titleLength | Specifies a pointer to the length of the title string (in bytes) including the terminating byte.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.l
VB Syntax

VB Sample Code for modifying title, options, margins, and date

Declare Function PEGetReportTitle Lib "crpe32.dll" (

    ByVal printJob As Integer, TitleHandle As Long, TitleLength As
Integer

    ) As Integer
Delphi Syntax
function PEGetReportTitle (

    printJob: Word;

    var titleHandle: HWnd;

    var titleLength: Word

    ): Bool stdcall;


PEGetReportVersion

Use PEGetReportVersion to retrieve the PEVersionInfo structure associated with the print job. The PEVersionInfo structure contains the reports version information.

C Syntax
BOOL CRPE_API PEGetReportVersion( short printJob,
                                  PEVersionInfo FAR* pVersionInfo )
Parameters

printJob | Specifies the print job from which you want to get the report version info.
pVersionInfo | Specifies a pointer to PEVersionInfo

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetReportVersion Lib "crpe32.dll" (ByVal printJob%,
pVersionInfo As PEVersionInfo) As Integer
Delphi Syntax
function PEGetReportVersion(
   printJob : Smallint;
   var pVersionInfo : PEVersionInfo): Bool stdcall;


PEGetSectionCode

Use PEGetSectionCode to retrieve the section code for the specified section. A section code indicates the section type (Page Header, Details, etc.). If there are multiple group sections it also identifies the group number, and if there are multiple sections in an area it identifies the section number. See Working with section codes.

C Syntax
short CRPE_API PEGetSectionCode (

        short printJob,

        short sectionN );
Parameters

printJob | Specifies the print job from which you want to retrieve a section code.
sectionN | Specifies the number of the section for which you want the section code. This parameter should be within the range obtained by PEGetNSections.

Returns
  • Returns the Section Codes, for the specified section.
  • Returns 0 if the call fails.
VB Syntax

VB Sample Code for modifying sections and lines

Declare Function PEGetSectionCode Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionN As Integer ) As Integer
Delphi Syntax

Delphi code for getting/setting section format

function PEGetSectionCode (

    printJob: Word;

    sectionN: Smallint

    ): Smallint stdcall;


PEGetSectionFormat

Use PEGetSectionFormat to retrieve the section format settings for selected sections in the specified report and supply them as member values for PESectionOptions. Use this function in order to update the section formats and pass them back using PESetSectionFormat.

C Syntax
BOOL CRPE_API PEGetSectionFormat (

        short printJob,

        short sectionCode,

        PESectionOptions FAR *options );
Parameters

printJob | Specifies the print job that you want to query to determine what report section options have been set using the Format Section dialog box.
sectionCode | Specifies theSection Codes, for the report section(s) for which you want to get section format information. See Working with section codes.
options | Specifies a pointer to PESectionOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for modifying sections and lines

Declare Function PEGetSectionFormat Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionCode As Integer,

    Options As PESectionOptions ) As Integer
Delphi Syntax

Delphi code for getting/setting section format

function PEGetSectionFormat (

    printJob: Word;

    sectionCode: integer;

    var options: PESectionOptions

    ): Bool stdcall;


PEGetSectionFormatFormula

Use PEGetSectionFormatFormula to retrieve the current format formula for the specified section of the report. Use this function with PEGetHandleString.

C Syntax
BOOL CRPE_API PEGetSectionFormatFormula (

        short printJob,

        short sectionCode,

        short formulaName,

        HANDLE FAR *textHandle,

        short FAR *textLength );
Parameters

printJob | Specifies the print job for which you want to retrieve the section format formula.
sectionCode | Specifies the Section Codes, for the report section(s) for which you want to get section format information. See Working with section codes.
formulaName | Specifies the name of the section format formula. Use one of the PE_FFN_XXX Area/Section Format Formula Constants.
textHandle | Specifies a pointer to the handle of the text of the actual formula.
textLength | Specifies a pointer to the length of the text string. Use this value to allocate a buffer for the text.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Not all formula names apply to all sections.
  • Use the value returned by textLength to allocate memory for a buffer. Use PEGetHandleString, to fill the buffer with the actual text of the formula.
VB Syntax
Declare Function PEGetSectionFormatFormula Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionCode As Integer,

    ByVal formulaName As Integer, textHandle As Long,

    textLength As Integer ) As Integer
Delphi Syntax
function PEGetSectionFormatFormula (

    printJob: Word;

    sectionCode: Word;

    formulaName: Word;

    var textHandle: HWnd;

    var textLength: Word

    ): Bool stdcall;


PEGetSectionHeight

Use PEGetSectionHeight to retrieve the section height information for the specified section. This is the replacement API Call for PEGetMinimumSectionHeight and should be used for all new development.

C Syntax
BOOL CRPE_API PEGetSectionHeight (

        short printJob,

        short sectionCode,

        short FAR *height );
Parameters

printJob | Specifies the print job that you want to query to retrieve section height information.
section Code | Specifies the Section Codes, for the report sections for which you want to retrieve information. See Working with section codes.
height | Specifies a pointer to the section height (in twips).

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetSectionHeight Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionCode As Integer,

    height As Integer ) As Integer
Delphi Syntax
function PEGetSectionHeight (

    printJob: Smallint;

    sectionCode: Smallint;

    Height: Smallint (*in twips*)

    ): Bool stdcall;


PEGetSelectedPrinter

Use PEGetSelectedPrinter to obtain information about the printer currently selected for the report. If a printer has been specified in Crystal Reports using the File|Printer Setup|Specific printer option, this call will return information about that printer. If the File|Printer Setup|Default printer option has been selected for the report, and custom options for the Default printer have been specified (Default Properties is toggled off in the Print Setup dialog box), information about the default printer specified under Windows Control Panel|Printers will be returned. If Default Properties is toggled on for the Default printer, this function will return a successful result, but the string handles will point to NULL strings.

C Syntax
BOOL CRPE_API PEGetSelectedPrinter (

        short printJob,

        HANDLE FAR *driverHandle,

        short FAR *driverLength,

        HANDLE FAR *printerHandle,

        short FAR *printerLength,

        HANDLE FAR *portHandle,

        short FAR *portLength,

    #if defined (WIN32)

        DEVMODEA FAR * FAR *mode

    #else

        DEVMODE FAR * FAR *mode

    #endif

        );
Parameters

l
printJob | Specifies the print job that you want to query to get information on the non-default printer that has been selected with the report.
driverHandle | Specifies a pointer to the handle of the printer driver for the printer that is selected with the print job.
driverLength | Specifies a pointer to the length of the printer driver name.
printerHandle | Specifies a pointer to the handle of the printer that is selected with the print job.
printerLength | Specifies a pointer to the length of the printer name.
portHandle | Specifies a pointer to the handle of the port to which the selected printer is connected.
portLength | Specifies a pointer to the length of the port name.
mode | Specifies a pointer to the DEVMODE, or DEVMODE Windows API structure.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Use PEGetHandleString, to obtain the actual strings pointed to by the string handles returned.
VB Syntax
Declare Function PEGetSelectedPrinter Lib "crpe32.dll" (

    ByVal printJob As Integer, DriverHandle As Long, DriverLength As
Integer,

    PrinterHandle As Long, PrinterLength As Integer, PortHandle As Long,

    PortLength As Integer, DevMode As Any ) As Integer
Delphi Syntax
function PEGetSelectedPrinter (

    printJob: Word;

    var driverHandle: Hwnd;

    var driverLength: Word;

    var printerHandle: Hwnd;

    var printerLength: Word;

    var portHandle: Hwnd;

    var portLength: Word;

    var mode: PDeviceModeA

    ): Bool stdcall;


PEGetSelectionFormula

Use PEGetSelectionFormula to retrieve the string handle for the selection formula used in the specified report. Use this function with PEGetHandleString. Use PESetSelectionFormula, to pass back the selection formula. The series can be used in a Custom-Print Link to identify and then change an existing record selection formula in response to a user selection at print time.

C Syntax
BOOL CRPE_API PEGetSelectionFormula (

        short printJob,

        HANDLE FAR *textHandle,

        short FAR *textLength );
Parameters

printJob | Specifies the print job for which you want to retrieve the selection formula string.
textHandle | Specifies a pointer to the handle of the string containing the formula text.
textLength | Specifies a pointer to the length of the formula string (in bytes) including the terminating byte.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for modifying selection formulas and group selection formulas

Declare Function PEGetSelectionFormula Lib "crpe32.dll" (ByVal printJob
As Integer, TextHandle As Long, TextLength As Integer) As Integer
Delphi Syntax
function PEGetSelectionFormula (

    printJob: Word;

    var textHandle: HWnd;

    var textLength: Word

    ): Bool stdcall;


PEGetSQLExpression

Use PEGetSQLExpression to retrieve a specified SQL expression in the specified report. Use this function with PEGetHandleString.

C Syntax
BOOL CRPE_API PEGetSQLExpression (

        short printJob,

        const char FAR *expressionName,

        HANDLE FAR *textHandle,

        short FAR *textLength );
Parameters

printJob | Specifies the print job for which you want to retrieve the SQL expression string.
expressionName | Specifies a pointer to the expression name.
textHandle | Specifies a pointer to the handle of the expression string.
textLength | Specifies a pointer to the length of the expression string.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEGetSQLExpression Lib "crpe32.dll" (ByVal printJob As
Integer, ByVal expressionName As String, textHandle As Long, textLength
As Integer) As Integer
Delphi Syntax
function PEGetSQLExpression (

    printJob: Smallint;

    const expressionName: PChar;

    var textHandle: Hwnd;

    var textLength: Smallint

    ): Bool stdcall;


PEGetSQLQuery

Use PEGetSQLQuery to retrieve the same query that appears in the Show SQL Query dialog box in Crystal Reports, in a syntax that's specific to the database driver you're using. Use this function with PEGetHandleString. Use PESetSQLQuery, to update the query. See Remarks below.

C Syntax
BOOL CRPE_API PEGetSQLQuery (

        short printJob,

        HANDLE FAR *textHandle,

        short FAR *textLength );
Parameters

printJob | Specifies the print job from which you want to retrieve the SQL query.
textHandle | Specifies a pointer to the handle of the string containing the SQL query string.
textLength | Specifies a pointer to the length of the SQL query string (in bytes) including the terminating byte.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

The report must be logged on before the call to PEGetSQLQuery is made.

VB Syntax

VB Sample Code for modifying SQL statements

Declare Function PEGetSQLQuery Lib "crpe32.dll" ( ByVal printJob As
Integer, TextHandle As Long, TextLength As Integer ) As Integer
Delphi Syntax

Delphi code for getting/setting the SQL query

function PEGetSQLQuery (

    printJob: Word;

    var textHandle: HWnd;

    var textLength: Word

    ): Bool stdcall;


PEGetSubreportInfo

Use PEGetSubreportInfo to retrieve information about the specified subreport.

C Syntax
BOOL CRPE_API PEGetSubreportInfo (

        short printJob,

        DWORD subreportHandle,

        PESubreportInfo FAR *subreportInfo );
Parameters

printJob | Specifies the primary report that contains the subreport about which you want to retrieve information.
subreportHandle | Specifies the handle of the subreport about which you want to retrieve information.
subreportInfo | Specifies a pointer to PESubreportInfo, which will be used for holding the information once it is retrieved.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for modifying Subreports

Declare Function PEGetSubreportInfo Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal subreportHandle As Long,

    subreportInfo As PESubreportInfo ) As Integer
Delphi Syntax

Delphi code for getting subreport information

function PEGetSubreportInfo (

    printJob: Word;

    subreportHandle: DWORD;

    var subreportInfo: PESubreportInfo

    ): Bool stdcall;


PEGetTrackCursorInfo

Use PEGetTrackCursorInfo to track cursors. Different cursors can be specified for different report areas and report objects in the preview window. This function retrieves cursor information for a specified job.

C Syntax
BOOL CRPE_API PEGetTrackCursorInfo (

        short printJob,

        PETrackCursorInfo FAR *cursorInfo );
Parameters

printJob | Specifies the print job for which you want to retrieve track cursor information.
cursorInfo | Specifies a pointer to PETrackCursorInfo, which will contain the track cursor information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Delphi Syntax
function PEGetTrackCursorInfo (

    printJob: smallint;

    var cursorInfo: PETrackCursorInfo

    ): Bool stdcall;


PEGetVersion

Use PEGetVersion to retrieve the version number of the DLL or the Crystal Report Engine. The high-order byte is the major version number and the low-order byte is the minor version number. This function can be used whenever you build functionality into a report that may not be available in earlier versions of the Crystal Report Engine and you need to verify the version number first. The function can be a handy safeguard for users who have more than one version of the Crystal Report Engine with the older version earlier in the path than the new version.

C Syntax
short CRPE_API PEGetVersion (

        short versionRequested );
Parameter

versionRequested | Specifies whether the DLL or Crystal Report Engine version is being requested. Use one of the following PE_GV_XXX constants.
 | Constant | Description
 | PE_GV_DLL | Returns the version of the DLL (CRPE/CRPE32).
 | PE_GV_ENGINE | Returns the version of the Crystal Report Engine.

Returns

Returns the version number of the DLL or the Crystal Report Engine.

VB Syntax
Declare Function PEGetVersion Lib "crpe32.dll" (ByVal version As
Integer)

    As Integer

The following simplifies the PEGetVersion call in Visual Basic.

Function PEVBGetVersion (ByVal component As Integer) As Single

    Dim version As Integer

    Dim major As Integer

    Dim minor As Integer

    version = PEGetVersion(component)

    If version = 0 Then

        PEVBGetVersion = 0

    Else

        major = version / 256

        minor = version Mod 256

        PEVBGetVersion = major + (minor / 10)

    End If

End Function
Delphi Syntax
function PEGetVersion (

    versionRequested: integer

    ): Smallint stdcall;
dBASE for Windows Syntax

EXTERN CWORD PEGetVersion (CWORD) CRPE.DLL


PEGetWindowHandle

Use PEGetWindowHandle to retrieve the handle of the preview window. This function can be used in a Custom-Print Link if you want to do something with the preview window (move it, change its size, etc.). PEGetWindowHandle can also be used to determine if the user has already closed the preview window.

C Syntax
HWND CRPE_API PEGetWindowHandle (

        short printJob );
Parameter

printJob

Specifies the print job for which you want to retrieve the preview window handle. If two or more preview windows are open, this function applies only to the most recently created preview window.

Returns
  • Returns the preview window handle if the call is successful.
  • Returns 0 if an error occurs or if the preview window has already been closed.
Remarks

This function can be used after PEStartPrintJob, and then, only if you have created a preview window.

VB Syntax

VB Sample Code for Previewing a Report

Declare Function PEGetWindowHandle Lib "crpe32.dll" (

    ByVal printJob As Integer ) As Long
Delphi Syntax
function PEGetWindowHandle (

    pr6intJob: Word

    ): HWnd stdcall;
dBASE for Windows Syntax

EXTERN CHANDLE PEGetWindowHandle (CWORD) CRPE.DLL


PEGetWindowOptions

Use PEGetWindowOptions to configure the preview window look and functionality. You can also determine whether the preview window has a group tree window; whether it can be drill down if there are hidden groups; and whether the close button, refresh button, and print setup button are shown, for example. This function returns the current report preview window configuration.

C Syntax
BOOL CRPE_API PEGetWindowOptions (

        short printJob,

        PEWindowOptions FAR *options );
Parameters

printJob | Specifies the print job from which you want to retrieve the preview window options. If two or more preview windows are open, this function applies only to the most recently created preview window.
PEWindowOptions | Specifies a pointer to PEWindowOptions, which will contain the retrieved information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

When hasGroupTree is True, it does not mean there will be a group tree in the preview window. The hasGroupTree option and the report option (Create Group Tree in Crystal Reports) together determine the group tree visibility in the preview window. Both options must be True for the group tree to be shown.

VB Syntax
Declare Function PEGetWindowOptions Lib "crpe32.dll" (

    ByVal printJob As Integer, Options As PEWindowOptions ) As Integer
Delphi Syntax
function PEGetWindowOptions (

    printJob: Word;

    var options: PEWindowOptions

    ):Bool stdcall;


PEHasSavedData

Use PEHasSavedData to determine if the specified report has data saved with it in memory. With this information, you can determine whether or not the data needs to be refreshed before the report is printed. See Remarks below.

C Syntax
BOOL CRPE_API PEHasSavedData (

        short printJob,

        BOOL FAR *hasSavedData );
Parameters

printJob | Specifies the handle of the print job you want to query to determine if it has saved data with it.
hasSavedData | Specifies a pointer to a Boolean value that indicates whether or not there is data saved with the report.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • A report may or may not have saved data when a print job is first opened from a report file. Since data is saved during a print, however, a report will always have saved data immediately after it is printed.
  • The default behavior is for a report to use its saved data rather than refresh its data from the database when printing a report.
  • Use PEDiscardSavedData, to release the saved data associated with a report. The next time the report is printed, it will get current data from the database.
VB Syntax

VB Sample Code for Custom Print Link

Declare Function PEHasSavedData Lib "crpe32.dll" (

    ByVal printJob As Integer, HasSavedData As Long ) As Integer
Delphi Syntax
function PEHasSavedData(

    printJob: Word;

    var hasSavedData: Bool

    ): Bool stdcall;


PEIsPrintJobFinished

Use PEIsPrintJobFinished to monitor the print job to see if it is finished or still in progress. You can use this function any time you have a call that is contingent on a print job being finished.

C Syntax
BOOL CRPE_API PEIsPrintJobFinished (

        short printJob );
Parameter

printJob

Specifies the print job that you want to query to determine if it has finished printing.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

PEIsPrintJobFinished will return TRUE immediately after the report has been displayed in the preview window, even if that preview window is still open.

VB Syntax
Declare Function PEIsPrintJobFinished Lib "crpe32.dll" (ByVal printJob _

        As Integer) As Integer
Delphi Syntax
function PEIsPrintJobFinished (

    printJob: Word

    ): Bool stdcall;
dBASE for Windows Syntax
EXTERN CLOGICAL PEIsPrintJobFinished (CWORD) CRPE.DLL


PELogOffServer

Use PELogOffServer to Log off the specified server. Use this call any time you have to log off a specified server.

C Syntax
BOOL CRPE_API PELogOffServer (

        const char FAR *dllName,

        PELogOnInfo FAR *logOnInfo );
Parameters

dllName | Specifies a pointer to the name of the Crystal Reports DLL for the datasource from which you want to log off (for example, "PDSODBC.DLL"). Note that the dllName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases and PDS*.DLL for SQL/ODBC databases.
logOnInfo | Specifies a pointer to PELogOnInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • PELogOnServer, and PELogOffServer can be called at any time to log on and off a database server. These functions are not required if the function PESetNthTableLogOnInfo, was already used to logon to a table.
  • This function requires a database DLL name which can be retrieved using PEGetNthTableType.
VB Syntax

VB Sample Code for modifying SQL statements

Declare Function PELogOffServer Lib "crpe32.dll" ( ByVal DLLName As
String, LogOnInfo As PELogOnInfo ) As Integer
Delphi Syntax

Delphi code for logging on/off a server

function PELogOffServer(

    dllName: PChar;

    var logOnInfo: PELogOnInfo

    ): Bool stdcall;


PELogOnServer

Use PELogOnServer to logon to the specified server.

C Syntax
BOOL CRPE_API PELogOnServer (

        const char FAR *dllName,

        PELogOnInfo FAR *logOnInfo );
Parameters

dllName | Specifies a pointer to the name of the Crystal Reports DLL for the server or password protected non-SQL table to which you want to logon. (for example, "PDSODBC.DLL"). Note that the dllName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases and PDS*.DLL for SQL/ODBC databases.
logOnInfo | Specifies a pointer to PELogOnInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • PELogOnServer and PELogOffServer, can be called at any time to log on and off a database server. These functions are not required if PESetNthTableLogOnInfo, was already used to set the password for a table.
  • This function requires a database DLL name, which can be retrieved using PEGetNthTableType.
  • This function can also be used for non-SQL tables, such as password-protected Paradox tables. Call this function to set the password for the Paradox DLL before beginning printing.
  • When printing using PEStartPrintJob, the ServerName passed in PELogOnServer does not need to agree exactly with the server name stored in the report. PELogOnServer can be used to switch to a different server or datasource at runtime.
  • The following points need to be considered when deciding whether to use PELogOnServer or PESetNthTableLogOnInfo.
      • PELogOnServer is easier to call than PESetNthTableLogOnInfo, and it can be called at any time. However, you must know the database DLL name to make this call.
      • PESetNthTableLogOnInfo is more flexible than PELogOnServer. It allows you to override any of the logon parameters. PESetNthTableLogOnInfo must be called after PEOpenPrintJob.
VB Syntax

VB Sample Code for modifying SQL statements

Declare Function PELogOnServer Lib "crpe32.dll" ( ByVal DLLName As
String, LogOnInfo As PELogOnInfo ) As Integer
Delphi Syntax

Delphi code for logging on/off a server

function PELogOnServer(

    dllName: PChar;

    var logOnInfo: PELogOnInfo

    ): Bool stdcall;


PELogOnSQLServerWithPrivateInfo

Use PELogOnSQLServerWithPrivateInfo to enable the Crystal Report Engine to "piggyback" your application's existing connection to a Server. If you are already logged on, this function lowers the number of connections established by a workstation, thus reducing application time and network traffic. It also prevents a Crystal Reports Log Off call from disconnecting an application's existing connection to the Server.

C Syntax
BOOL CRPE_API PELogOnSQLServerWithPrivateInfo (

        const char FAR *dllName,

        void FAR *privateInfo );
Parameters

dllName | Specifies a pointer to the name of the Crystal Reports DLL that was used in establishing the connection to the server when the report was first created. For example, if a report was created using an ODBC datasource, the Crystal Reports DLL is PDSODBC.DLL.
privateInfo | In the application, a connection to the server has to have been established and this in turn generates a Handle to a Database Connection (HDBC). This parameter specifies the application's handle to the connection. This makes Crystal Reports aware of the existing connection so it can use it instead of establishing a new one. Since the reports with which this function works are based on ODBC, this parameter is actually an ODBC HDBC.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

If the application uses ODBC to connect, get the ODBC HDBC by using the following function calls. Also, see the ODBC documentation for more information.

SQLAllocEnv

«Initializes the ODBC call level interface and allocates memory for an
environment handle.»

SQLAllocConnect

«Returns an ODBC HDBC.»
VB Syntax
Declare Function PELogOnSQLServerWithPrivateInfo Lib "crpe32.dll" (
ByVal DLLName As String, ByVal PrivateInfo As Long ) As Integer
Delphi Syntax
function PELogOnSQLServerWithPrivateInfo (

    dllName: PChar;

    privateInfo: Pointer

    ): Bool stdcall;


PENextPrintWindowMagnification

Use PENextPrintWindowMagnification to change the preview window magnification to the next magnification level in sequence. Use this function to cycle through the three levels of preview window magnification (Full Page, Fit One Side, Fit Both Sides, Full Page, Fit One Side, etc.) whenever the report has been printed to a preview window.

C Syntax
BOOL CRPE_API PENextPrintWindowMagnification (

        short printJob );
Parameter

printJob

Specifies the print job displayed in the preview window for which you want to step the magnification level.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for Previewing a Report

Declare Function PENextPrintWindowMagnification Lib "crpe32.dll" (ByVal

    printJob As Integer ) As Integer
Delphi Syntax
function PENextPrintWindowMagnification (

    printJob: Word

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PENextPrintWindowMagnification (CWORD) CRPE.DLL


PEOpenEngine

Use PEOpenEngine to prepare the Crystal Report Engine (in single-thread mode) for requests. This function is a necessary part of any Custom-Print Link. It is also required for any Print-Only Link in which you want the report to print to a window that is to remain visible after the report is printed. It is not necessary to use this function with a Print-Only Link if the report is directed to a printer.

C Syntax

BOOL CRPE_API PEOpenEngine (void);

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • This function must be called before any other Crystal Report Engine function. If an error occurs in the PEOpenEngine function call, PEGetErrorCode, can be passed a print job value of zero to obtain error information.
  • PEOpenEngine opens the print engine in single-thread mode by default.
VB Syntax

VB Sample Code for Previewing a Report

Declare Function PEOpenEngine Lib "crpe32.dll" () As Integer

Delphi Syntax

Delphi code for opening and closing the Print Engine

function PEOpenEngine

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PEOpenEngineEx () CRPE.DLL


PEOpenPrintJob

Use PEOpenPrintJob to prepare to print a report and return a handle which identifies that particular print job. The handle returned must be used in all subsequent calls related to that print job which require that information. This function is used as a mandatory part of a Custom-Print Link to retrieve the print job handle which is then used when required as parameter printJob in each additional Custom-Print Link function call.

C Syntax
short PEOpenPrintJob (

        const char *reportFilePath );
Parameter

reportFilePath

Specifies the file name and path of the report that you want to open. You must enclose this parameter in quotes.

Returns
  • Returns the job number.
  • Returns 0 if the report file does not exist or if an error occurs.
Remarks
  • This function must be called before most other Crystal Report Engine functions are used.
  • Only one print job can be configured at a time.
  • PEClosePrintJob, must be called later to close the job.
  • Report Path\Filename must be enclosed in quotes.
      • For example, PEOpenPrintJob ("C:\CRW\REPORT1.RPT");
      • Note: In C or C++, the slashes (\) in the string must be entered as double slashes (\\).
  • This function opens the print job with the printer selected in the report (via the File|Printer Setup menu command) or the default printer (if no replacement printer has been selected in the report).
VB Syntax

VB Sample Code for Previewing a Report

Declare Function PEOpenPrintJob Lib "crpe32.dll" (ByVal RptName As
String) _

        As Integer
Delphi Syntax

Delphi code for opening and closing a PrintJob

function PEOpenPrintJob (

    reportFilePath: PChar

    ): Smallint stdcall;
dBASE for Windows Syntax

EXTERN CWORD PEOpenPrintJob (CSTRING) CRPE.DLL


PEOpenSubreport

Use PEOpenSubreport to open the named subreport and return a number that identifies that subreport.
The number returned must be used in all subsequent calls related to the subreport (where a print job handle is required).

C Syntax
short CRPE_API PEOpenSubreport (

        short parentJob,

        char FAR *subreportName );
Parameters

parentJob | Specifies the primary report (the report that contains the subreport). This is the handle returned from PEOpenPrintJob.
subreportName | Specifies a pointer to the name of the subreport that you want to open. This is retrieved using PEGetSubreportInfo.

Returns
  • Returns the job number of the subreport.
  • Returns 0 if the subreport does not exist or if an error occurs.
Remarks
  • This function must be called before any other Crystal Report Engine functions related to the subreport.
  • PECloseSubreport must be called later to close the job.
VB Syntax
Declare Function PEOpenSubreport Lib "crpe32.dll" (

    ByVal parentJob As Integer, ByVal subreportName As String ) As
Integer
Delphi Syntax
function PEOpenSubreport (

    parentJob: Word;

    subreportName: PChar

    ): Word stdcall;


PEOutputToPrinter

Use PEOutputToPrinter to direct output to a printer. See Remarks below.

C Syntax
BOOL CRPE_API PEOutputToPrinter (

        short printJob,

        short nCopies );
Parameters

printJob | Specifies the print job that you want to send to a printer.
nCopies | Specifies the number of report copies that you want to print. Pass 0 to preserve the existing setting.

Returns
  • TRUE if the output can be sent to the printer successfully.
  • FALSE if the output cannot be sent to the printer.
Remarks
  • If a printer has been specified via PESelectPrinter, output will be sent to that printer.
  • If there is no PESelectPrinter selection but there is a printer specified in the report via the Print|Select Printer menu command, output will be sent to that printer.
  • If there is no PESelectPrinter selection and there is no printer specified in the report, output will be to the Windows default printer.
  • PEOpenPrintJob, opens the print job with the printer specified in the report (if there is one) or with the Windows default printer (if no printer is specified in the report).
  • The sequence of calls that follows may help to explain printer output concepts as well as potential problems. Assume that a printer is specified in the report via the Print|Select Printer menu command. Make certain to sequence your function calls to get the output desired.
      • PEOpenPrintJob

        // Opens the job with printer specified in report, or, if none
        // is specified, the Windows default printer. The printer the
        // job opens with is Printer #1.

      • PEOutputToWindow

        // Directs the output to the preview window.

      • PEStartPrintJob

        // Report is printed in the preview window based on Printer #1.

      • PEOutputToPrinter

        // Directs output to the printer.

      • PESelectPrinter

        // Specifies 2nd printer, Printer #2. This overrides Printer #1.

      • PEStartPrintJob

        // Report is printed on Printer #2. Window output and printer
        // output are based on two different printers and may cause
        // confusion.

      • PEClosePrintJob
  • If one printer is set for landscape output, for example, and the other for portrait output, the sequence of calls above will print an entirely different report in the preview window than what actually appears on paper.
  • This function supersedes PEOutputToDefaultPrinter which was available in earlier versions of the Crystal Report Engine.
VB Syntax

VB Sample Code for Custom Print Link

Declare Function PEOutputToPrinter Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal nCopies As Integer ) As Integer
Delphi Syntax
function PEOutputToPrinter (

    printJob: Word;

    nCopies: integer

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PEOutputToPrinter (CWORD, CWORD) CRPE.DLL


PEOutputToWindow

Use PEOutputToWindow to direct printed output to a preview window. This function is used as part of a Custom-Print Link whenever you want the report printed to the preview window instead of to the printer.

C Syntax
BOOL CRPE_API PEOutputToWindow (

        short printJob,

        const char FAR *title,

        int left,

        int top,

        int width,

        int height,

        DWORD style,

        HWND parentWindow );
Parameters

printJob | Specifies the print job you want to print in the preview window.
title | Specifies a pointer to the null-terminated string that contains the title that you want to appear in the preview window title bar.
left | Specifies the x coordinate of the upper left corner of the preview window, in pixels. See Remarks below.
top | Specifies the y coordinate of the upper left corner of the preview window, in pixels. See Remarks below.
width | Specifies the width of the preview window, in pixels.
height | Specifies the height of the preview window, in pixels.
style | Specifies the style of the window being created. Style settings can be combined using the bitwise "OR" operator. You can specify any of the following window styles. Also, see Remarks below.
 | Constant | Value | Description
 | WS_MINIMIZE | 536870912 | Make a window of minimum size.
 | WS_VISIBLE | 268435456 | Make a window that is visible when it first appears (for overlapping and pop-up windows).
 | WS_DISABLED | 134217728 | Make a window that is disabled when it first appears.
 | WS_CLIPSIBLINGS | 67108864 | Clip child windows with respect to one another.
 | WS_CLIPCHILDREN | 33554432 | Exclude the area occupied by child windows when drawing inside the parent window.
 | WS_MAXIMIZE | 16777216 | Make a window of maximum size.
 | WS_CAPTION | 12582912 | Make a window that includes a title bar.
 | WS_BORDER | 8388608 | Make a window that includes a border.
 | WS_DLGFRAME | 4194304 | Make a window that has a double border but no title.
 | WS_VSCROLL | 2097152 | Make a window that includes a vertical scroll bar.
 | WS_HSCROLL | 1048576 | Make a window that includes a horizontal scroll bar.
 | WS_SYSMENU | 524288 | Include the system menu box.
 | WS_THICKFRAME | 262144 | Include the thick frame that can be used to size the window.
 | WS_MINIMIZEBOX | 131072 | Include the minimize box.
 | WS_MAXIMIZEBOX | 65536 | Include the maximize box.
 | CW_USEDFAULT | -32768 | Assign the child window the default horizontal and vertical position, and the default height and width.
parentWindow | Specifies the handle of the parentWindow if the preview window is a child of that window.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • For a top-level preview window, the top left corner is relative to the origin of the screen. For an MDI child preview window, the top left corner is relative to the origin of the frame window's client area. For a child preview window, the top left corner is relative to the origin of the parent window's client area.
  • If parentWindow is NULL, the preview window is a top-level window (that is, not a child of any other window). For a top-level preview window, the top left corner is relative to the origin of the screen. Left and top can be CW_USDEFAULT to put the window at a default location. Width and height can also be CW_USEDEFAULT to give the window a default size.
  • If the MDI frame window parent handle is specified, the report preview window will show up in the client area of the MDI parent. If the MDI frame window child window handle is specified (child window must be created) the report preview window will show up in the child window.
  • If parentWindow is the handle of some other window, the preview window is a child of that window. For a child preview window, the top left corner is relative to the origin of the parent window's client area.
  • If the preview window is a top-level window or an MDI child window and style is 0, the following style is used instead.

    (WS_VISIBLE | WS_THICKFRAME | WS_SYSMENU | WS_MAXIMIZEBOX | WS_MINIMIZEBOX)

      • That is, the default window is a visible window with a thick frame that can be used for sizing the window. The window includes a system menu box, and a maximize and minimize box.
  • The preview window is created when PEStartPrintJob, is called.
VB Syntax

VB Sample Code for Previewing a Report

Declare Function PEOutputToWindow Lib "crpe32.dll" (ByVal printJob As
Integer, ByVal Title As String, ByVal Left As Long, ByVal Top As Long,
ByVal Width As Long, ByVal Height As Long, ByVal style As Long, ByVal
PWindow As Long) As Integer

Visual Basic developers can cut and paste a declaration for CW_USEDEFAULT into their application.

  • For VB 4, cut the declaration from c:\vb\winapi\win32api.txt
  • For VB 3, cut the declaration from c:\vb\winapi\win30api.txt
Delphi Syntax
function PEOutputToWindow (

    printJob: Word;

    title: PChar;

    left: longint;

    top: longint;

    width: longint;

    height: longint;

    style: longint;

    parentWindow: HWnd

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PEOutputToWindow (CWORD, CSTRING, CWORD, CWORD, CWORD, CWORD, CLONG, CHANDLE) CRPE.DLL


PEPrintControlsShowing

Use PEPrintControlsShowing to determine if the print controls are displayed in the preview window. Use this function to retrieve the visible print controls and pass back using PEShowPrintControls.

C Syntax
BOOL CRPE_API PEPrintControlsShowing (

        short printJob,

        BOOL FAR *controlsShowing );
Parameters

printJob | Specifies the print job for which you want to determine whether or not the print controls will be displayed when the job is sent to a preview window.
controlsShowing | Specifies a pointer to a TRUE value if the print controls will be shown or FALSE value if they will be hidden.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for Previewing a Report

Declare Function PEPrintControlsShowing Lib "crpe32.dll" (

    ByVal printJob As Integer, ControlsShowing As Long ) As Integer
Delphi Syntax
function PEPrintControlsShowing (

    printJob: Word;

    var controlsShowing: Bool

    ): Bool stdcall;


PEPrintReport

Use PEPrintReport to print the specified report to either the printer or to a preview window. This function establishes a Print-Only Link where changes made during runtime by other PE calls are ignored. Use PEPrintReport any time that you simply want to print a report from an application without giving the user the ability to customize the report.

C Syntax
short CRPE_API PEPrintReport (

        const char FAR *reportFilePath,

        BOOL toDefaultPrinter,

        BOOL toWindow,

        const char FAR *title,

        int left,

        int top,

        int width,

        int height,

        DWORD style,

        HWND parentWindow );
Parameters

reportFilePath | Specifies a pointer to the NULL-terminated string that contains the name and path of the report that you want to print.
toDefaultPrinter | Specifies whether or not the report is to be sent to the default printer.
toWindow | Specifies whether or not the report is to be displayed in the preview window.
title | Specifies a pointer to the NULL-terminated string that contains the title you want to appear on the title bar if you are printing the report to a window.
left | Specifies the x coordinate of the upper left hand corner of the preview window, in pixels.
top | Specifies the y coordinate of the upper left hand corner of the preview window, in pixels.
width | Specifies the width of the preview window, in pixels.
height | Specifies the height of the preview window, in pixels.
style | Specifies the style of the window being created. Style settings can be combined using the bitwise "OR" operator. Select your style from the list that appears with PEOutputToWindow.
parentWindow | Specifies the handle of the parent window if the preview window is a child of that window.

Returns
  • Returns PE_ERR_NOERROR if the call was successful.
  • Returns another Error Codes, if the call failed.
VB Syntax

VB Sample Code for Previewing a Report

Declare Function PEPrintReport Lib "crpe32.dll" (ByVal RptName As
String, ByVal Printer As Integer, ByVal Window As Integer, ByVal Title As
String, ByVal Lft As Long, ByVal Top As Long, ByVal Wdth As Long, ByVal
Height As Long, ByVal Style As Long, ByVal PWindow As Long) As Integer
Delphi Syntax
function PEPrintReport (

    reportFilePath: PChar;

    toDefaultPrinter: Bool;

    toWindow: Bool;

    title: PChar;

    left: integer;

    top: integer;

    width: integer;

    height: integer;

    style: longint;

    parentWindow: HWnd

    ): Smallint stdcall;
dBASE for Windows Syntax

EXTERN CWORD PEPrintReport (CSTRING, CLOGICAL, CLOGICAL, CSTRING, CWORD, CWORD, CWORD, CWORD, CLONG, CHANDLE) CRPE.DLL


PEPrintWindow

Use PEPrintWindow to print the report that is displayed in the preview window. This function can be used in a Custom-Print Link to enable the user to preview the report in the preview window, and then, if everything looks satisfactory, to print the report to the printer in response to a user event.

C Syntax
BOOL CRPE_API PEPrintWindow (

        short printJob,

        BOOL waitUntilDone );
Parameters

printJob | Specifies the print job displayed in the preview window that you want to print.
waitUntilDone | BOOL. Reserved. This parameter must always be set to TRUE.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for Previewing a Report

Declare Function PEPrintWindow Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal WaitNoWait As Integer ) As Integer
Delphi Syntax
function PEPrintWindow (

    printJob: Word;

    waitUntilDone: Bool

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PEPrintWindow (CWORD, CLOGICAL) CRPE.DLL


PEReimportSubreport

Use PEReimportSubreport to reimport a subreport into the specified main report.

C Syntax
BOOL CRPE_API PEReimportSubreport (

    short printJob,

    DWORD subreportHandle,

    BOOL FAR *linkChanged,

    BOOL FAR *reimported );
Parameters

printJob | Specifies the print job for which you want to reimport a subreport.
subreportHandle | Specifies the handle of the subreport that you want to reimport.
linkChanged | Specifies a pointer to a Boolean value indicating whether or not the link has changed. See Remarks below.
reimported | Specifies a pointer to a Boolean value indicating whether or not the subreport has been reimported. See Remarks below.

Returns
  • TRUE if the call is successful and the subreport is up-to-date or was reimported with fixed or
    missing links.
  • FALSE if the call fails, the subreport path is invalid, or the reimport failed. The specific error that occurred can be retrieved with PEGetErrorCode.
Remarks
  • Parameter linkChanged
      • will be set to FALSE if the subreport is reloaded and the links are fixed.
      • will be set to TRUE if the subreport is reloaded but missing links.
  • Parameter reimported
      • will be set to FALSE if the subreport is up-to-date, or if the reimport failed due to an invalid path or other error.
      • will be set to TRUE if the subreport was reloaded with links fixed or missing.
VB Syntax
Declare Function PEReimportSubreport Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal subreportHandle As Long,

    linkChanged As Long, reimported As Long ) As Integer


PESelectPrinter

Use PESelectPrinter to specify a printer other than the default printer as the print destination for the specified print job. You can use this function to enable the user to select a printer other than the default printer at print time. One way of doing this is to have your application call the Print Setup common dialog box.

C Syntax
BOOL CRPE_API PESelectPrinter (

        short printJob,

        const char FAR *driverName,

        const char FAR *printerName,

        const char FAR *portName,

        DEVMODEA FAR *mode );
Parameters

printJob | Specifies the print job for which you want to select a printer.
driverName | Specifies a pointer to a null-terminated string that contains the name of the printer driver for the selected printer.
printerName | Specifies a pointer to a null-terminated string that contains the printer name for the selected printer.
portName | Specifies a pointer to a null-terminated string that contains the port name for the port to which the selected printer is attached.
mode | Specifies a pointer to the DEVMODE, Windows API structure.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • The PRINTDLG structure returned by the Windows API PrintDlg function contains handles to DEVMODEA and DEVNAMES structures. This information can be used to obtain driverName, printerName, portName, and mode values for PESelectPrinter.
  • Your code must parse the return from the dialog box selection and insert the returned Printer Driver Name, Printer Name, and Port Name as parameters in the call.
  • After selecting the printer with this call, you can direct the output to that printer (using PEOutputToPrinter) or to the preview window (using PEOutputToWindow).
  • This call will override a printer selection that you built into the report at design time via the Crystal Reports Select Printer menu command.
  • If you follow this call with the call PEOutputToWindow, the report appears in the
    preview window.
  • To revert to the default printer, pass 0 for each parameter.
  • The driver name and printer name must exist on your machine.
  • You can specify a different printer port than that assigned to the selected printer on your machine.
  • For parameter mode, use 0 for the default mode or create a DEVMODE, structure to customize (if your development tool supports such a structure).
  • This function should be called before PEStartPrintJob, or the results may be inconsistent or unexpected.
VB Syntax
Declare Function PESelectPrinter Lib "crpe32.dll" ( ByVal printJob As
Integer,

    ByVal PrinterDriver As String, ByVal PrinterName As String,

    ByVal PortName As String, DevMode As Any ) As Integer
Delphi Syntax
function PESelectPrinter(

    printJob: Word;

    driverName: PChar;

    printerName: PChar;

    portName: PChar;

    mode: PDeviceModeA

    ): Bool stdcall;


PESetAllowPromptDialog

Use PESetAllowPromptDialogto specify whether prompting for parameter values is allowed during printing.

C Syntax
BOOL CRPE_API PESetAllowPromptDialog (

        short printJob,

        BOOL showPromptDialog );
Parameters

printJob | Specifies the print job.
showPromptDialog | If TRUE, then prompting is allowed.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PESetAllowPromptDialog Lib "crpe32.dll" (ByVal _

    printJob As Integer, ByVal showPromptDialog As Integer) As Integer
Delphi Syntax
function PESetAllowPromptDialog (

    printJob: Smallint;

    showPromptDialog: Bool

    ): Bool stdcall;


PESetAreaFormat

Use PESetAreaFormat to set the area format settings for selected areas in the specified report to the values in PESectionOptions. This function can be used to provide specialized formatting for printing invoices, form letters, printing to pre-printed forms, etc. It allows you to hide an area, insert a page break either before or after an area begins, reset the page number to 1 after a group value prints, prevent page breaks from spreading data from a single record over two pages, and to print group values only at the bottom of a page.

C Syntax
BOOL CRPE_API PESetAreaFormat (

        short printJob,

        short areaCode,

        PESectionOptions FAR *options );
Parameters

printJob | Specifies the print job for which you want to set area formatting options.
areaCode | Specifies the Section Codes for the report area for which you want to set formatting options. See the information on area codes in Working with section codes.
options | Specifies a pointer to PESectionOptions. Use this structure to set your section options.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

This function should be called before PEStartPrintJob, or the results may be inconsistent or unexpected.

VB Syntax
Declare Function PESetAreaFormat Lib "crpe32.dll" ( ByVal printJob As
Integer,

    ByVal areaCode As Integer, Options As PESectionOptions ) As Integer
Delphi Syntax
function PESetAreaFormat (

    printJob: Word;

    areaCode: Integer;

    var options: PESectionOptions

    ): Bool stdcall;


PESetAreaFormatFormula

Use PESetAreaFormatFormula to change the specified area format formula to the formula string you supply as a parameter. This function will only change the text of a formula which already exists in the report; you cannot use it to add a formula. When you give the user the ability to change the formula at print time, your link must include code to replace the formulaString parameter with a user-generated value.

C Syntax
BOOL CRPE_API PESetAreaFormatFormula (

        short printJob,

        short areaCode,

        short formulaName,

        const char FAR *formulaString );
Parameters

printJob | Specifies the print job for which you want to set a new format formula string.
areaCode | Specifies the Section Codes for the report area for which you want to set formatting options. See Working with section codes.
formulaName | Specifies the name of the formatting formula for which you want to supply a new string. Use one of the PE_FFN_XXX Area/Section Format Formula Constants.
formulaString | Specifies a pointer to the null-terminated string that you want to assign to the format formula.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
  • Error code PE_ERR_BADFORMULANAME if the formula does not exist.
  • Error code PE_ERR_BADFORMULATEXT if there is an error in the formula.
Remarks
  • This function should be called before PEStartPrintJob, or the results may be inconsistent or unexpected.
  • Not all parameters apply to all areas.
VB Syntax
Declare Function PESetAreaFormatFormula Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal areaCode As Integer,

    ByVal formulaName As Integer, ByVal formulaString As String ) As
Integer
Delphi Syntax
function PESetAreaFormatFormula(

    printJob: Word;

    areaCode: Word;

    formulaName: Word;

    formulaString: Pchar

    ): Bool stdcall;


PESetDialogParentWindow

Use PESetDialogParentWindow to set the handle for the parent window of CRPE dialog boxes (that is, Print Progress dialog box).

C Syntax
BOOL CRPE_API PESetDialogParentWindow (

        short printJob,

        HWND parentWindow );
Parameters

printJob | Specifies the print job for which you want to specify a parent window.
parentWindow | Specifies the handle of the parent window.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for Custom Print Link

Declare Function PESetDialogParentWindow Lib "crpe32.dll" (ByVal
printJob _

        As Integer, ByVal parentWindow As Long) As Integer
Delphi Syntax
function PESetDialogParentWindow (

    printJob: Word;

    parentWindow: HWnd

    ): Bool stdcall;


PESetEventCallback

Use PESetEventCallback to set the event callback function for the specified job. CRPE can fire certain events when something happens inside CRPE. CRPE will call the callback function and notify what kind of event has or is about to occur. Within callbackProc, the user can interpret the event ID and perform the proper process.

C Syntax
BOOL CRPE_API PESetEventCallback (

        short printJob,

        BOOL (CALLBACK *callbackProc)

            (short eventID, void *param, void *userData)

        void *userData );
Parameters

printJob | Specifies the print job for which you want to create an Event callback procedure.
callbackProc | The CALLBACK procedure that will handle your Crystal Report Engine events. This should be a pointer to a standard Windows CALLBACK procedure. Refer to the Windows SDK for information on creating CALLBACK procedures.
userData | Specifies a pointer to any information you want to pass to the Event handling CALLBACK procedure. The pointer will be available in the userData member of the procedure. This value can be 0.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Each job can have only one callback function.
  • The Event procedure functions passed in the callbackProc parameter should be a standard Windows CALLBACK procedure. Refer to documentation on the Windows API for information on creating CALLBACK procedures.
  • If you need to pass data to callbackProc using the userData parameter of callbackProc, be sure the memory allocated for the data does not fall out of scope or gets deallocated before the callbackProc is called by Windows. If this happens, the data will be unavailable and errors may occur in your application.
  • For a complete example of how to use this function, see Handling preview window events.
  • If callbackProc returns TRUE, a CRPE default action will be provided. If callbackProc returns FALSE, a CRPE default action will not be used. The user should be responsible for providing default behavior. For some events, the callbackProc return value is ignored. The following list gives the description of different events supported by CRPE.
PE_ACTIVATE_PRINT_WINDOW_EVENT
  • Called
    Before the preview window becomes active.
  • Parameter
    Pointer to PEGeneralPrintWindowEventInfo.
  • Return
    Ignored.
PE_CANCEL_BUTTON_CLICKED_EVENT
  • Called
    After clicking the cancel button; before canceling the printing or reading the database.
  • Parameter
    Pointer to PEGeneralPrintWindowEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_CLOSE_BUTTON_CLICKED_EVENT
  • Called
    After clicking the close button; before closing the preview window.
  • Parameter
    Pointer to PECloseButtonClickedEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
  • Remarks
    If FALSE is returned before actually closing the preview window, a PE_CLOSE_PRINT_WINDOW_EVENT is fired.
PE_CLOSE_PRINT_WINDOW_EVENT
  • Called
    Before the preview window is closed.
  • Parameter
    Pointer to PEGeneralPrintWindowEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_DEACTIVATE_PRINT_WINDOW_EVENT
  • Called
    Before the preview window becomes in active.
  • Parameter
    Pointer to PEGeneralPrintWindowEventInfo.
  • Return
    Ignored.
PE_DRILL_ON_DETAIL_EVENT
  • Called
    After double-clicking one of the detail areas in the preview window.
  • Parameter
    Pointer to PEDrillOnDetailEventInfo.
  • Return
    Ignored.
PE_DRILL_ON_GROUP_EVENT
  • Called
    After clicking on one of the group tree nodes, double-clicking or Ctrl-clicking a node with the magnify glass cursor, or double-clicking one of the groups in the preview window; before showing the group. This event also applies to drilling on a graph.
  • Parameter
    Pointer to PEDrillOnGroupEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_DRILL_ON_HYPERLINK_EVENT
  • Called
    Whenever the user double-clicked on an object with a hyperlink (and the hyperlink is about to be executed).
  • Parameter
    Pointer toPEHyperlinkEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_EXPORT_BUTTON_CLICKED_EVENT
  • Called
    After Export button is clicked; before export process starts.
  • Parameter
    Pointer to PEGeneralPrintWindowEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_FIRST_PAGE_BUTTON_CLICKED_EVENT
  • Called
    After clicking the first page button; before going to the first page.
  • Parameter
    Pointer to PEGeneralPrintWindowEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_GROUP_TREE_BUTTON_CLICKED_EVENT
  • Called
    After clicking the group tree button; before showing or hiding the group tree.
  • Parameter
    Pointer to PEGeneralPrintWindowEventInfo.
  • Return
    Ignored.
PE_LAST_PAGE_BUTTON_CLICKED_EVENT
  • Called
    After clicking the last page button; before going to the last page.
  • Parameter
    Pointer to PEGeneralPrintWindowEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_LAUNCH_SEAGATE_ANALYSIS_EVENT
  • Called
    Whenever the Launch Seagate Analysis toolbar button is clicked.

    Note: Seagate Analysis is now known as Crystal Analysis.

  • Parameter
    Pointer toPELaunchSeagateAnalysisEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_LEFT_CLICK_EVENT
  • Called
    Whenever the left mouse button has been clicked over the preview window.
  • Parameter
    Pointer toPEMouseClickEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_MAPPING_FIELD_EVENT
  • Called
    Whenever the user calls PEVerifyDatabase and the field mapping method has been set to PE_FM_EVENT_DEFINED_FLD_MAP. The field mapping method can be retrieved and set with PEGetFieldMappingType, and PESetFieldMappingType.
  • Parameter
    Pointer toPEFieldMappingEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_MIDDLE_CLICK_EVENT
  • Called
    Whenever the middle mouse button has been clicked over the preview window.
  • Parameter
    Pointer toPEMouseClickEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_NEXT_PAGE_BUTTON_CLICKED_EVENT
  • Called
    After clicking the next page button, before going to the next page.
  • Parameter
    Pointer to PEGeneralPrintWindowEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_PREVIOUS_PAGE_BUTTON_CLICKED_EVENT
  • Called
    After clicking the previous page button; before going to the previous page.
  • Parameter
    Pointer to PEGeneralPrintWindowEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_PRINT_BUTTON_CLICKED_EVENT
  • Called
    After the Print button is clicked; before printing process starts.
  • Parameter
    Pointer to PEGeneralPrintWindowEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_PRINT_SETUP_BUTTON_CLICKED_EVENT
  • Called
    After clicking Print Setup button; before showing the Print Setup dialog box.
  • Parameter
    Pointer to PEGeneralPrintWindowEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_READING_RECORDS_EVENT
  • Called
    This event is fired during a reading database or regenerating saved data process. It is fired after a specified amount of time, not aver reading every record.
  • Parameter
    Pointer to PEReadingRecordsEventInfo.
  • Return
    Ignored.
PE_REFRESH_BUTTON_CLICKED_EVENT
  • Called
    After clicking the Refresh button; before refreshing the data.
  • Parameter
    Pointer to PEGeneralPrintWindowEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_RIGHT_CLICK_EVENT
  • Called
    Whenever the right mouse button has been clicked over the preview window.
  • Parameter
    Pointer toPEMouseClickEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_SEARCH_BUTTON_CLICKED_EVENT
  • Called
    After the search button is clicked; before the search starts.
  • Parameter
    Pointer to PESearchButtonClickedEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_SHOW_GROUP_EVENT
  • Called
    After clicking one of the group tree nodes; before showing that group.
  • Parameter
    Pointer to PEShowGroupEventInfo.
  • Return
    TRUE to use the default action. FALSE to cancel the default action.
PE_START_EVENT
  • Called
    Before the Report Engine starts a process. A process can be printing to printer, exporting, printing to a window, or generating pages when navigating through the preview window.
  • Parameter
    Pointer toPEStartEventInfo.
  • Return
    TRUE to use the default action; FALSE to cancel the default action.
PE_STOP_EVENT
  • Called
    Whenever a process has finished. Used in conjunction with PE_START_EVENT.
  • Parameter
    Pointer toPEStopEventInfo.
  • Return
    Ignored.
PE_ZOOM_LEVEL_CHANGING_EVENT
  • Called
    After changing zoom control; before changing preview zoom level.
  • Parameter
    Pointer to PEZoomLevelChangingEventInfo.
  • Return
    Ignored.
Delphi Syntax
function PESetEventCallback(

    printJob: Word;

    callbackProc: pointer

        {Callback Function should be of form:

        Function callbacProc(eventID: smallint;

                    param: pointer;

                    userData: pointer)}

    ): Bool stdcall;


PESetFieldMappingType

Use PESetFieldMappingType to set the field mapping type code for the specified report.

C Syntax
BOOL CRPE_API PESetFieldMappingType

        short printJob,

        WORD mappingType );
Parameters

printJob | Specifies the print job for which you want to set the field mapping type code.
mappingType | The field mapping type code that you want to set. Use one of the PE_FM_XXX Field Mapping Type Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Unmapped report fields will be removed.
  • If mappingType = PE_FM_EVENT_DEFINED_FLD_MAP, you need to activate the PE_MAPPING_FIELD_EVENT and define a callback function.
VB Syntax
Declare Function PESetFieldMappingType Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal mappingType As Integer ) As Integer
Delphi Syntax
function PESetFieldMappingType (

    printJob: smallint;

    mappingType: Word

    ): BOOL stdcall;


PESetFont

Use PESetFont to set the font for field and/or text characters in the report section(s) specified. Use this call any time you need to change a default font at runtime in response to user input or to specify a built-in printer font.

C Syntax
BOOL CRPE_API PESetFont (

        short printJob,

        short sectionCode,

        short scopeCode,

        const char FAR *faceName,

        short fontFamily,

        short fontPitch,

        short charSet,

        short pointSize,

        short isItalic,

        short isUnderlined,

        short isStruckOut,

        short weight );
Parameters

printJob | Specifies the print job for which you want to select a font.
sectionCode | Specifies the Section Codes for the report section(s) for which you want to select a font. See Working with section codes.
scopeCode | Specifies whether the font selected is to apply to fields only, to text only, or to both fields and text. To specify both fields and text, use the OR operator. Use one of the following codes.
 | Constant | Description
 | PE_FIELDS | Sets the default font for all field values in the report section specified.
 | PE_TEXT | Sets the default font for all text (that has not been entered as a field value) in the report section specified.
faceName | Specifies a pointer to the actual face name of the font you want to use. The face name you pass can typically come from a Font dialog box, be hard coded in the application or be chosen by the application from the fonts supported on the printer. Example: "Times New Roman". Pass 0 for no change.
fontFamily | Specifies the font family for the font you want to use. Use one of the following FF_XXX constants.
 | Constant | Description
 | FF_DONTCARE | No change.
 | FF_ROMAN | Variable pitch font with serifs.
 | FF_SWISS | Fixed pitch font without serifs.
 | FF_MODERN | Fixed-pitch font, with or without serifs.
 | FF_SCRIPT | Handwriting-like font.
 | FF_DECORATIVE | Fancy display font.
fontPitch | Specifies the font pitch you wish to use. Use a constant value for the font pitch as defined in WINDOWS.H. Use DEFAULT_PITCH if you wish to retain the current default.
 | Constant | Description
 | DEFAULT_PITCH | 0X00
 | FIXED_PITCH | 0X01
 | VARIABLE_PITCH | 0X02
charSet | Specifies the character set you wish to use. Use a constant value for the character set as defined in WINDOWS.H. Use DEFAULT_CHARSET if you wish to retain the current default.
 | Constant | Value
 | ANSI_CHARSET | 0
 | DEFAULT_ CHARSET | 1
 | SYMBOL_ CHARSET | 2
 | SHIFTJIS_ CHARSET | 128
 | HANGEUL_ CHARSET | 129
 | CHINESEBIG5_ CHARSET | 136
 | OEM_CHARSET | 255
pointSize | Specifies the desired point size for the selected font. Pass 0 for no change.
isItalic | Specifies whether the font selected should be italicized. Pass TRUE for Italic font, FALSE for non-Italic font, or PE_UNCHANGED to use the current default setting.
isUnderlined | Specifies whether the font selected should be underlined. Pass TRUE for Underline, FALSE for no Underline, or PE_UNCHANGED to use the current default setting.
isStruckOut | Specifies whether the font selected should be struck out. Pass TRUE for StrickOut, FALSE for no StrickOut, or PE_UNCHANGED to use the current default setting.
weight | Specifies the weight of the font. Use a constant value from the weight values defined in WINDOWS.H. Pass 0 for no change.
 | Constant | Value
 | FW_DONTCARE | 0
 | FW_THIN | 100
 | FW_EXTRALIGHT | 200
 | FW_LIGHT | 300
 | FW_NORMAL | 400
 | FW_MEDIUM | 500
 | FW_SEMIBOLD | 600
 | FW_BOLD | 700
 | FW_EXTRABOLD | 800
 | FW_HEAVY | 900
 | FW_ULTRALIGHT | FW_EXTRALIGHT
 | FW_REGULAR | FW_NORMAL
 | FW_DEMIBOLD | FW_SEMIBOLD
 | FW_ULTRABOLD | FW_EXTRABOLD
 | FW_BLACK | FW_HEAVY

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

This command includes a number of parameters:

  • For the fontFamily, fontPitch, charSet, and weight parameters, use constant values from the font family, pitch, character set, and width defined in WINDOWS.H. Use 0 for each parameter that is not to be changed from the current default.
  • For the faceName parameter, enter the actual name of the font. Enter 0 for no change.
  • faceName, fontFamily, fontPitch, and charSet should all be specified whenever one of these parameters is specified. Use fontFamily = FF_DONTCARE, fontPitch = DEFAULT_PITCH, or charSet = DEFAULT_CHARSET to leave the default values unchanged.
  • This function should be called before PEStartPrintJob, or the results may be inconsistent or unexpected.
VB Syntax
Declare Function PESetFont Lib "crpe32.dll" ( ByVal printJob As Integer,

    ByVal sectionCode As Integer, ByVal ScopeCode As Integer,

    ByVal FaceName As String, ByVal FontFamily As Integer,

    ByVal FontPitch As Integer, ByVal CharSet As Integer,

    ByVal PointSize As Integer, ByVal isItalic As Integer,

    ByVal isUnderlined As Integer, ByVal isStruckOut As Integer,

    ByVal Weight As Integer ) As Integer
Delpli Syntax
function PESetFont(

    printJob: Word;

    sectionCode: integer;

    scopeCode: integer;

    faceName: PChar;

    fontFamily: integer;

    fontPitch: integer;

    charSet: integer;

    pointSize: integer;

    isItalic: integer;

    isUnderlined: integer;

    isStruckOut: integer;

    weight: integer

    ): Bool stdcall;
dBASE for Windows Syntax
EXTERN CLOGICAL PESetFont (CWORD, CWORD, CWORD, CSTRING, CWORD, CWORD,
CWORD, CWORD, CWORD, CWORD, CWORD, CWORD) CRPE.DLL


PESetFormula

Use PESetFormula to change the specified formula to the formula string you supply as a parameter. This function will only change the text of a formula which already exists in the report; you cannot use it to add a new formula. This function can be used by itself to replace the formula string for a known formula.

This function can also be used as one of a series of functions (PEGetFormula; PEGetHandleString; and PESetFormula). The series can be used in a Custom-Print Link to identify and then change an existing formula at print time in response to a user selection. When you give the user the ability to change the formula at print time, your link must include code to replace formulaString with a user-generated value.

C Syntax
BOOL CRPE_API PESetFormula (

        short printJob,

        const char *formulaName,

        const char FAR *formulaString );
Parameters

printJob | Specifies the print job for which you want to set a new formula string.
formulaName | Specifies a pointer to the null-terminated string that contains the name of the formula for which you want to set a new formula string.
formulaString | Specifies a pointer to the null-terminated string that you want to replace the existing formula string.

Returns
  • TRUE if the call is successful.
  • FALSE if the named formula does not exist.
  • Error code PE_ERR_BADFORMULANAME if the formula does not exist.
  • Error code PE_ERR_BADFORMULATEXT if there is an error in the formula.
Remarks
  • This function should be called before PEStartPrintJob or the results may be inconsistent or unexpected.
  • You cannot use this function to set conditional formulas.
VB Syntax

VB Sample Code for modifying formulas

Declare Function PESetFormula Lib "crpe32.dll" (ByVal printJob As
Integer, ByVal FormulaName As String, ByVal FormulaString As String) As
Integer
Delphi Syntax

Delphi code for getting/setting formulas

function PESetFormula (

    printJob: Word;

    formulaName: PChar;

    formulaString: PChar

    ): Bool stdcall;
dBASE for Windows Syntax
EXTERN CLOGICAL PESetFormula (CWORD, CSTRING, CSTRING) CRPE.DLL


PESetFormulaSyntax

Use PESetFormulaSyntax to set the formula syntax information to use for the next and all subsequent formula API call.

C Syntax
BOOL CRPE_API PESetFormulaSyntax (

    short printJob,

    PEFormulaSyntax FAR *formulaSyntax );
Parameters

printJob | Specifies the print job for which you want to set formula syntax.
formulaSyntax | Specifies a pointer to PEFormulaSyntax, which will contain the information that you want to set.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • If any Formula API is called before PESetFormulaSyntax is called, then the default PE_FST_CRYSTAL is assumed.
  • For running total condition formula:
      • formulaSyntax[0] is the syntax for the evalFormula.
      • formulaSyntax[1] is the syntax for the reset formula.
VB Syntax
Declare Function PESetFormulaSyntax Lib "crpe32.dll" (

    ByVal printJob As Integer, formulaSyntax As PEFormulaSyntax ) As
Integer


PESetGraphAxisInfo

Use PESetGraphAxisInfo to set the several chart axis options that are available.

C Syntax
BOOL CRPE_API PESetGraphAxisInfo (

        short printJob,

        short sectionN,

        short graphN,

        PEGraphAxisInfo FAR * graphAxisInfo );
Parameters

printJob | Specifies the print job for which you want to set chart axis information.
sectionN | Specifies the section of the report containing the chart for which you want to set chart axis information.
graphN | Specifies for which chart within the section you want to set the chart axis information. This value is 0-based. Charts are numbered based on their order of insertion into the report.
graphAxisInfo | Specifies a pointer to PEGraphAxisInfo, which will contain the new information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PESetGraphAxisInfo Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionN As Integer,

    ByVal graphN As Integer, graphAxisInfo As PEGraphAxisInfo ) As
Integer
Delphi Syntax
function PESetGraphAxisInfo (

  printJob          : Smallint;

  sectionN          : Smallint;

  graphN            : Smallint;

  var graphAxisInfo : PEGraphAxisInfo): Bool; {$ifdef WIN32} stdcall;
{$endif}


PESetGraphFontInfo

Use PESetGraphFontInfo to set the font information for the specified chart.

C Syntax
BOOL CRPE_API PESetGraphFontInfo (

        short printJob,

        short sectionN,

        short graphN,

        WORD titleFontType,

        PEFontColorInfo FAR *fontColourInfo );
Parameters

printJob | Specifies the print job for which you want to set chart font information.
sectionN | Specifies the number of the section in which the chart appears. This parameter should be within the range obtained by PEGetNSections.
graphN | Specifies for which chart within the section you want to set the font information. This value is 0-based. Charts are numbered based on their order of insertion into the report.
titleFontType | Uses one of the PE_GTF_XXX Graph Text Font Constants
fontColourInfo | Specifies a pointer to PEFontColorInfo,which will contain the new information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PESetGraphFontInfo Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionN As Integer,

    ByVal graphN As Integer, ByVal titleFontType As Integer,

    fontColourInfo As PEFontColorInfo ) As Integer
Delphi Syntax
function PESetGraphFontInfo (

  printJob           : Smallint;

  sectionN           : Smallint;

  graphN             : Smallint;

  titleFontType      : Word;

  var fontColourInfo : PEFontColorInfo): Bool; {$ifdef WIN32}
stdcall;{$endif}


PESetGraphOptionInfo

Use PESetGraphOptionInfo to set display options for the specified chart.

C Syntax
BOOL CRPE_API PESetGraphOptionInfo (

        short printJob,

        short sectionN,

        short graphN,

        PEGraphOptionInfo FAR *graphOptionInfo );
Parameters

printJob | Specifies the print job for which you want to set chart display information.
sectionN | Specifies the number of the section in which the chart appears. This parameter should be within the range obtained by PEGetNSections.
graphN | Specifies for which chart within the section you want to set the chart display information. This value is 0-based. Charts are numbered based on their order of insertion into the report.
graphOptionInfo | Specifies a pointer to PEGraphOptionInfo, which will contain the new information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PESetGraphOptionInfo Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionN As Integer,

    ByVal graphN As Integer, graphOptionInfo As PEGraphOptionInfo ) As
Integer
Delphi Syntax
function PESetGraphOptionInfo (

  printJob           : Smallint;

  sectionN           : Smallint;

  graphN             : Smallint;

  var graphOptionInfo : PEGraphOptionInfo): Bool; {$ifdef WIN32}

         stdcall; {$endif}


PESetGraphTextDefaultOption

Use PESetGraphTextDefaultInfo to enable or disable chart title defaults.

C Syntax
BOOL CRPE_API PESetGraphTextDefaultOption (

    short printJob,

    short sectionN,

    short graphN,

    WORD titleType,

    BOOL useDefault );
Parameters

printJob | Specifies the print job for which you want to enable/disable chart title default option information.
sectionN | Specifies the 0-based index number of the section in which the chart appears. This parameter should be within the range obtained by PEGetNSections.
graphN | Specifies the 0-based index number of the chart for which you want to enable/disable the chart text default option information. Charts are numbered based on their order of insertion into the report.
titleType | Specifies the title type. Use one of the PE_GTT_XXX Graph Title Type Constants.
useDefault | Specifies the Boolean value indicating whether or not chart title defaults are enabled.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PESetGraphTextDefaultOption Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionN As Integer,

    ByVal graphN As Integer, ByVal titleType As Integer,

    ByVal useDefault As Long ) As Integer


PESetGraphTextInfo

Use PESetGraphTextInfo to set the title text information for the specified chart.

C Syntax
BOOL CRPE_API PESetGraphTextInfo (

        short printJob,

        short sectionN,

        short graphN,

        WORD titleType,

        LPCSTR title );
Parameters

printJob | Specifies the print job for which you want to set title text information.
sectionN | Specifies the 0-based index number of the section in which the chart appears. This parameter should be within the range obtained by PEGetNSections.
graphN | Specifies the 0-based index number of the chart for which you want to set the title text information. Charts are numbered based on their order of insertion into the report.
titleType | Specifies the title type. Use one of the PE_GTT_XXX Graph Title Type Constants.
title | Specifies a pointer to the string containing the title text.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PESetGraphTextInfo Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionN As Integer,

    ByVal graphN As Integer, ByVal titleType As Integer,

    ByVal title As String ) As Integer
Delphi Syntax
function PESetGraphTextInfo (

  printJob  : Smallint;

  sectionN  : Smallint;

  graphN    : Smallint;

  titleType : Word;

  title     : PChar): Bool; {$ifdef WIN32} stdcall; {$endif}


PESetGraphTypeInfo

Use PESetGraphTypeInfo to set the type of the specified chart.

C Syntax
BOOL CRPE_API PESetGraphTypeInfo (

        short printJob,

        short sectionN,

        short graphN,

        PEGraphTypeInfo FAR *graphTypeInfo );
Parameters

printJob | Specifies the print job for which you want to set chart type information.
sectionN | Specifies the number of the section in which the chart appears. This parameter should be within the range obtained by PEGetNSections.
graphN | Specifies for which chart within the section you want to set the type. This value is 0-based. Charts are numbered based on their order of insertion into the report.
graphTypeInfo | Specifies a pointer to PEGraphTypeInfo, which will contain the new information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PESetGraphTypeInfo Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionN As Integer,

    ByVal graphN As Integer, graphTypeInfo As PEGraphTypeInfo ) As
Integer
Delphi Syntax
function PESetGraphTypeInfo (

  printJob          : Smallint;

  sectionN          : Smallint;

  graphN            : Smallint;

  var graphTypeInfo : PEGraphTypeInfo): Bool; {$ifdef WIN32} stdcall;
{$endif}


PESetGroupCondition

Use PESetGroupCondition to change the group condition for a group section. Use this function whenever you want to change the grouping at print time, for example, to print one report grouped in several different ways.

C Syntax
BOOL CRPE_API PESetGroupCondition (

        short printJob,

        short sectionCode,

        const char FAR *conditionField,

        short condition,

        short sortDirection );
Parameters

printJob | Specifies the print job for which you want to change the group condition for a group section.
sectionCode | Specifies the code for the report section for which you want to set the group condition. See Working with section codes.
conditionField | Specifies a pointer to the name of the field that triggers a summary whenever its value changes. This parameter is a result of calling PEGetHandleString, with conditionFieldHandle and conditionFieldLength, returned by PEGetGroupCondition.
condition | Specifies the condition that will trigger a summary. Use one of the PE_GC_XXX Group Condition Constants. Note that the constants available are different for different field types.
sortDirection | Use one of the PE_SF_XXX Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • No default values are allowed. You must specify a value for all parameters when using this function.
  • If you have a formula that references a summary field and you change the condition on the summary field without fixing the formula, you will get an error.
  • This function should be called before PEStartPrintJobor the results may be inconsistent or unexpected.
VB Syntax
Declare Function PESetGroupCondition Lib "crpe32.dll" (ByVal printJob As
Integer, ByVal sectionCode As Integer, ByVal ConditionField As String,
ByVal Condition As Integer, ByVal SortDirection As Integer) As Integer
Delphi Syntax
function PESetGroupCondition (

    printJob: Word;

    sectionCode: smallint;

    conditionField: PChar;

    condition: smallint;

    sortDirection: smallint

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PESetGroupCondition (CWORD, CWORD, CSTRING, CWORD, CWORD) CRPE.DLL


PESetGroupOptions

Use PESetGroupOptions to set grouping options for the specified group.

C Syntax
BOOL CRPE_API PESetGroupOptions (

        short printJob,

        short groupN,

        PEGroupOptions FAR *groupOptions );
Parameters

printJob | Specifies the print job for which you wish to set grouping options.
groupN | Specifies the 0-based group level number.
groupOptions | Specifies a pointer to PEGroupOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • This function should be called before PEStartPrintJob or the results may be inconsistent or unexpected.
  • If you are using PESetGroupOptions to set the top/bottom N sort field, all the group sort fields related to the group will be deleted and a new one specified by the group options will be added.
VB Syntax
Declare Function PESetGroupOptions Lib "crpe32.dll" (ByVal printJob As
Integer, ByVal groupN As Integer, groupOptions As PEGroupOptions) As
Integer
Delphi Syntax
function PESetGroupOptions (

    printJob: Word;

    groupN: smallint;

    var groupOptions: PEGroupOptions

    ): Bool; stdcall;


PESetGroupSelectionFormula

Use PESetGroupSelectionFormula to change the group selection formula to the formula string you supply as a parameter. This function can be used by itself to replace an existing group selection formula and also as one of a series of functions (PEGetGroupSelectionFormula; PEGetHandleString; and PESetGroupSelectionFormula). The series can be used in a Custom-Print Link to identify and then change an existing group selection formula at print time in response to a user selection. When you give the user the ability to change the group selection formula at print time, your link must include code to replace formulaString with a user-generated value.

C Syntax
BOOL CRPE_API PESetGroupSelectionFormula (

        short printJob,

        const char FAR *formulaString );
Parameters

printJob | Specifies the print job for which you want to set a new group selection formula.
formulaString | Specifies a pointer to the null-terminated string you want to assign to the group selection formula.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails due to an internal error (for example, the connection to the database fails).
Remarks
  • Immediately after setting the new formula with PESetGroupSelectionFormula, the new formula should be verified with PECheckGroupSelectionFormula.
  • This function should be called before PEStartPrintJob or the results may be inconsistent or unexpected.
VB Syntax

VB Sample Code for modifying selection formulas and group selection formulas

Declare Function PESetGroupSelectionFormula Lib "crpe32.dll" (ByVal printJob As Integer, ByVal formulaString As String) As Integer

Delphi Syntax
function PESetGroupSelectionFormula (

    printJob: Word;

    formulaString: PChar

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PESetGroupSelectionFormula (CWORD, CSTRING) CRPE.DLL


PESetMargins

Use PESetMargins to set the page margins for the specified report to the values you supply as parameters. Use this function any time you want to set the printer margins at runtime in response to user specifications.

C Syntax
BOOL CRPE_API PESetMargins (

        short printJob,

        short left,

        short right,

        short top,

        short bottom );
Parameters

For each margin parameter, specify the margin in twips or PM_SM_DEFAULT to use the corresponding default margin for the currently selected printer. See Remarks below.

printJob | Specifies the print job for which you want to set new margins.
left | Specifies the left margin.
right | Specifies the right margin.
top | Specifies the top margin.
bottom | Specifies the bottom margin.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • This function should be called before PEStartPrintJob, or the results may be inconsistent or unexpected.
  • A twip is 1/1440 of an inch; there are 20 twips in a point. To set .5" margins, for example, you would enter the value 720.
VB Syntax

VB Sample Code for modifying title, options, margins, and date

Declare Function PESetMargins Lib "crpe32.dll" ( ByVal printJob As
Integer,

    ByVal LeftMargin As Integer, ByVal RightMargin As Integer,

    ByVal TopMargin As Integer, ByVal BottomMargin As Integer ) As
Integer
Delphi Syntax
function PESetMargins (

    printJob: Word;

    left: Word;

    right: Word;

    top: Word;

    bottom: Word

    ): Bool stdcall;
dBASE for Windows Syntax
EXTERN CLOGICAL PESetMargins (CWORD, CWORD, CWORD, CWORD, CWORD)
CRPE.DLL


PESetNDetailCopies

Use PESetNDetailCopies to print multiple copies of the Details section of the report. For example, you can use this function to print multiple copies of labels for a customer, multiple copies of a purchase order, or multiple copies of anything set up in the Details section of your report. To retrieve the number of times each Details section is to be printed, use PEGetNDetailCopies.

C Syntax
BOOL CRPE_API PESetNDetailCopies (

        short printJob,

        short nDetailCopies );
Parameters

printJob | Specifies the print job for which you want set the number of copies to print.
nDetailCopies | Specifies the number of report copies you want to print.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • This function should be called before PEStartPrintJob, or the results may be inconsistent or unexpected.
  • To change top/bottom N group sorting order, use PESetGroupOptions.
VB Syntax

VB Sample Code for modifying sections and lines

Declare Function PESetNDetailCopies Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal nDetailCopies As Integer ) As
Integer
Delphi Syntax
function PESetNDetailCopies(

    printJob: Word;

    nDetailCopies: smallint;

    ): Bool stdcall;
dBASE for Windows Syntax
EXTERN CLOGICAL PESetNDetailCopies (CWORD, CWORD) CRPE.DLL


PESetNthAlertConditionFormula

Use PESetNthAlertConditionFormula to set the condition formula for the specified Report Alert associated with the print job.

C Syntax
BOOL CRPE_API PESetNthAlertConditionFormula (short printJob,
                                         short alertN,
                                         constant char FAR * formula);
Parameters

printJob | Specifies the print job for which you want to set the Report Alert condition formula.
alertN | Specifies the Report Alert for which you want to set the Report Alert condition formula.
formula | Specifies a pointer to the string containing the condition formula to set for the Report Alert.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

The condition formula can be based on recurring records or on summary fields, but cannot be based on print-time fields, such as running totals or print time formulas. Condition formulas cannot have shared variables.

VB Syntax
Declare Function PESetNthAlertConditionFormula Lib "crpe32.dll" (ByVal
printJob%, ByVal alertN%, formula As String) As Integer
Delphi Syntax
function PESetNthAlertConditionFormula(
   printJob : Smallint;
   alertN : Smallint;
   const formula : PCHAR) : boolean stdcall;


PESetNthAlertDefaultMessage

Use PESetNthAlertDefaultMessage to set the default message for the specified Report Alert associated with the print job.

C Syntax
BOOL CRPE_API PESetNthDefaultMessage (short printJob,
                                         short alertN,
                                         constant char FAR * text);
Parameters

printJob | Specifies the print job for which you want to set the Report Alerts default message.
alertN | Specifies the Report Alert for which you want to set the default message.
text | Specifies a pointer to the string containing the default message for the Report Alert.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PESetNthAlertDefaultMessage Lib "crpe32.dll" (ByVal
printJob%, ByVal alertN%, text As String) As Integer
Delphi Syntax
function PESetNthAlertDefaultMessage(
   printJob : Smallint;
   alertN : Smallint;
   const text : PCHAR) : boolean stdcall;


PESetNthAlertMessageFormula

Use PESetNthAlertMessageFormula to set the message formula for the specified Report Alert associated with the print job.

C Syntax
BOOL CRPE_API PESetNthAlertMessageFormula (short printJob,
                                           short alertN,
                                           const char FAR *formula);
Parameters

printJob | Specifies the print job for which you want to set the Report Alert's message.formula.
alertN | Specifies the Report Alert for which you want to set the message.formula.
formula | Specifies a pointer to the string containing the message.formula for the Report Alert.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

The result of the formula must be a string. If PESetNthAlertMessageFormula is set it will override the value set for the Report Alerts default message.

VB Syntax
Declare Function PESetNthAlertMessageFormula Lib "crpe32.dll" (ByVal
printJob%, ByVal alertN%, formula As String) As Integer
Delphi Syntax
function PESetNthAlertMessageFormula(
   printJob : Smallint;
   alertN : Smallint;
   const formula : PCHAR) : boolean stdcall;


PESetNthGroupSortField

Use PESetNthGroupSortField to set one of the group sort fields in the specified report. This function can only be used to modify an existing sort field and direction when the sort field number, name, and direction are known.

Note: Note: PESetNthGroupSortField cannot be used to create a new sort field.

The function can also be used as one of a series of functions (PEGetNGroupSortFields, called once; PEGetNthGroupSortField, or PEGetHandleString, called as many times as needed to identify the correct group sort field; and PESetNthGroupSortField called once, when the correct group sort field is identified). The series can be used in a Custom-Print Link to identify and then change an existing group sort field and/or sort order in response to a user selection at print time. When you give the user the ability to specify group sort field(s) and/or direction at print time, your link must include code to replace name and/or direction with user-generated values.

C Syntax
BOOL CRPE_API PESetNthGroupSortField (

        short printJob,

        short sortFieldN,

        const char FAR *name,

        short direction );
Parameters

printJob | Specifies the print job for which you want to set a group sort field.
sortFieldN | Specifies the 0-based number of the sort field you want to set. The first sort field is field 0. If the report has N sort fields, the function can be called with sortFieldN between 0 and N-1. If the report has N sort fields, you can call the function with sortFieldN = N to add a new sort field to the end of the list of existing sort fields. If N=0, the function will create the first sort field.
name | Specifies a pointer to the null-terminated string that contains the name of the group sort field.
direction | Specifies the sort directions. Use one of the PE_SF_XXX Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

This function should be called before PEStartPrintJob, or the results may be inconsistent or unexpected.

VB Syntax

VB Sample Code for sorting groups

Declare Function PESetNthGroupSortField Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal sortFieldN As Integer, _

    ByVal SortGroupName As String, ByVal Direction As Integer ) As
Integer
Delphi Syntax
function PESetNthGroupSortField (

    printJob: Word;

    sortFieldN: smallint;

     name: PChar;

     direction: smallint

     ): Bool stdcall;
dBASE for Windows Syntax
EXTERN CLOGICAL PESetNthGroupSortField (CWORD, CWORD, CSTRING, CWORD)
CRPE.DLL


PESetNthParameterDefaultValue

Use PESetNthParameterDefaultValue to set a default value for a specified parameter field in a report. Use PEGetNParameterDefaultValues, to retrieve the number of default values for the parameter field.

C Syntax
BOOL CRPE_API PESetNthParameterDefaultValue (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName,

        short index,

        PEValueInfo FAR *valueInfo );
Parameters

printJob | Specifies the print job for which you want to set a parameter default value.
parameterField Name | Specifies a pointer to the string containing the parameter field name.
reportName | Specifies a pointer to the string containing the report name. See Remarks below.
index | Specifies the index number of the default value to be set.
valueInfo | Specifies a pointer to PEValueInfo, which will contain the default value.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax
Declare function PESetNthParameterDefaultValue Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, ByVal index As Integer, _

    valueInfo As PEValueInfo ) As Integer
Delphi Syntax
function PESetNthParameterDefaultValue (

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar;

    index: smallint;

    var valueInfo: PEValueInfo

    ): BOOL stdcall;


PESetNthParameterField

Use PESetNthParameterField to set a value for the specified parameter field. For new development, see Remarks below.

C Syntax
BOOL CRPE_API PESetNthParameterField (

        short printJob,

        short parameterN,

        PEParameterFieldInfo FAR *parameterInfo );
Parameters

printJob | Specifies the print job for which you want to set a parameter field value.
parameterN | Specifies the number of the parameter field in the report.
parameterInfo | Specifies a pointer to PEParameterFieldInfo which is used to pass the parameter field value information. See Remarks below.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • For new development, the Default/CurrentValueSet members of PEParameterFieldInfo must be set to FALSE and the following new calls used to access default and current value lists.
      • PEAddParameterCurrentRange
      • PEAddParameterCurrentValue
      • PEAddParameterDefaultValue
      • PESetNthParameterDefaultValue
  • To if you wish to set the parameter field to NULL then use CRWNULL (for example, ParameterFieldInfo.currentValue = CRWNULL). It is of Type String and independent of the data type of the parameter. See PEParameterFieldInfo.
  • To determine if a parameter field is a stored procedure, use PEGetNthParameterType or PEGetNthParameterField functions.
  • This function should be called before PEStartPrintJob or the results may be inconsistent or unexpected.
Visual Basic Syntax
Declare Function PESetNthParameterField Lib "crpe32.dll" _

    (ByVal printJob     As Integer, ByVal varN As Integer, varInfo As _

    PEParameterFieldInfo) As Integer
Delphi Syntax
function PESetNthParameterField (

    printJob: Word;

    varN: Smallint;

    var varInfo: PEParameterFieldInfo

    ): Bool stdcall;


PESetNthParameterValueDescription

Use PESetNthParameterValueDescription to set the description of the value for a parameter.

C Syntax
BOOL CRPE_API PESetNthParameterValueDescription (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName,

        short index,

        char FAR *valueDesc );
Parameters

printJob | Specifies the print job for which you want to set parameter value description information.
parameterFieldName | Specifies a pointer to the parameterFieldName for which you want to set the parameter value description.
reportName | Specifies a pointer to the report name. See Remarks below.
index | Specifies the index.
valueDesc | Specifies a pointer to the handle of the value description to be set.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax
Declare Function PESetNthParameterValueDescription Lib "crpe32.dll" (_

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, ByVal index As Integer, _

    ByVal valueDesc As String ) As Integer
Delphi Syntax
function PESetNthParameterValueDescription (

  printJob            : Smallint;

  parameterFieldName  : PChar;

  reportName          : PChar;

  index               : Smallint;

  valueDesc           : PChar): Bool; {$ifdef WIN32} stdcall; {$endif}


PESetNthSortField

Use PESetNthSortField to set one of the sort fields in the specified report. This function can be used by itself to set a sort field/direction when there is not one already set, or to change a sort field/direction when the number and name of the sort field are known.

The function can also be used as one of a series of functions (PEGetNSortFields, called once; var reportAlertInfo : PEReportAlertInfo) : boolean stdcall;, or PEGetHandleString, called together as many times as needed to identify the correct sort field; and PESetNthSortField, called once when the correct sort field is identified). The series can be used in a Custom-Print Link to identify and then change an existing sort field and/or sort order in response to a user selection at print time. When you give the user the ability to specify sort field(s) and/or direction at print time, your link must include code to replace name and/or sort direction with user-generated values.

C Syntax
BOOL CRPE_API PESetNthSortField (

        short printJob,

        short sortFieldN,

        const char FAR *name,

        short direction );
Parameters

printJob | Specifies the print job for which you want to set sort field information.
sortFieldN | Specifies the 0-based number of the sort fields that you want to set. The first sort field is field 0. If the report has N sort fields, the function can be called with sortFieldN between 0 and N-1 to replace an existing sort field. If the report has N sort fields, you can call the function with sortFieldN = N to add a new sort field to the end of the list of existing sort fields. If N=0, the function will add the first sort field.
name | Specifies a pointer to the null-terminated string that contains the name of the sort field.
direction | Specifies the sort direction. Use one of the PE_SF_XXX Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

This function should be called before PEStartPrintJob or the results may be inconsistent or unexpected.

VB Syntax

VB Sample Code for sorting records

Declare Function PESetNthSortField Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal sortNumber As Integer, _

    ByVal SortFieldName As String, ByVal Direction As Integer ) As
Integer
Delphi Syntax
function PESetNthSortField (

    printJob: Word;

    sortFieldN: smallint;

    name: PChar;

    direction: smallint

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PESetNthSortField (CWORD, CWORD, CSTRING, CWORD) CRPE.DLL


PESetNthTableLocation

Use PESetNthTableLocation to set the location for a selected table in the specified print job. This function is typically combined with PEGetNthTableLocation to identify the location of a table and then to change it.

C Syntax
BOOL CRPE_API PESetNthTableLocation (

        short printJob,

        short tableN,

        PETableLocation FAR *location );
Parameters

printJob | Specifies the handle of the print job for which you want to set a table's location.
tableN | Specifies the 0-based number of the table for which you want to set a new location. The first table is table 0. The last table is N-1.
location | Specifies the pointer to PETableLocation. The format of the string will be depend on the type of database specified.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PESetNthTableLocation Lib "crpe32.dll" ( ByVal printJob
As Integer, ByVal TableN As Integer, Location As PETableLocation ) As
Integer
Delphi Syntax
function PESetNthTableLocation(

    printJob: Word;

    tableN: smallint;

     var location: PETableLocation

     ): Bool stdcall;


PESetNthTableLogOnInfo

Use PESetNthTableLogOnInfo to set the log on information for the specified print job to the values in PELogOnInfo.

C Syntax
BOOL CRPE_API PESetNthTableLogOnInfo (

    short printJob,

    short tableN,

    PELogOnInfo FAR *logOnInfo,

    BOOL propagateAcrossTables );
Parameters

printJob | Specifies the print job for which you want to set table log on information.
tableN | Specifies the 0-based number of the table for which you want to set log on information. The first table is table 0. The last table is N-1.
logOnInfo | Specifies a pointer to the PELogOnInfo.
propagateAcrossTables | If set to TRUE, the program will apply the new log on information to any other tables in the report that had the same original server and database names as the specified table. If set to FALSE, the program will apply the new log on information only to the table specified.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • See PELogOnServer for additional comments regarding PELogOnInfo.
  • The program logs on when printing the report, but you must first set the correct log on information using PESetNthTableLogOnInfo. Logging off is performed automatically when the print job is closed.
  • You must supply at least the password with this function. You can pass empty strings ("") for the other parameters or, alternatively, you can change the server, database, and/or user ID by entering the appropriate strings.
  • When you create a report from a single database (for example, one .MDB file with multiple tables), set the propagateAcrossTables parameter to TRUE. This insures that the changes are made to all tables in the .MDB file (thus avoiding the necessity to code the changes for each table individually).
  • This function can be used to set the location of an Essbase application and database used by a report. For complete information, see PELogOnInfo.
VB Syntax

VB Sample Code for modifying database table settings

Declare Function PESetNthTableLogOnInfo Lib "crpe32.dll" ( ByVal
printJob As Integer, ByVal TableN As Integer, LogOnInfo As PELogOnInfo,
ByVal Propagate As Integer ) As Integer
Delphi Syntax

Delphi code for logging on/off a server

function PESetNthTableLogOnInfo (

    printJob: Word;

    tableN: smallint;

    var logOnInfo: PELogOnInfo;

    propagateAcrossTables: Bool

    ): Bool stdcall;


PESetNthTablePrivateInfo

Use PESetNthTablePrivateInfo to set the information needed for using data objects such as ADO, RDO, or CDO with the Active Data Driver (PS2MON.DLL).

C Syntax
BOOL CRPE_API PESetNthTablePrivateInfo (

        short printJob,

        short tableN,

        PETablePrivateInfo FAR *privateInfo );
Parameters

printJob | Specifies the print job for which you want to change the MS Access session information.
tableN | Specifies the 0-based number of the table for which you want to set table private information. The first table is table 0. The last table is N-1.
privateInfo | Specifies a pointer to PETablePrivateInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails
Remarks

The PESetNthTablePrivateInfo function is used in conjunction with the Crystal Report Print Engine (Crpe32.dll) in a Visual C++ application. If you are using Visual Basic see SetActiveDataSource.

Delphi Syntax
       function PESetNthTablePrivateInfo (

               printJob: Smallint;

               tableN:   Smallint;

               var privateInfo:         PETablePrivateInfo

       )    :Bool; {$ifdef WIN32} stdcall; {$endif}


PESetNthTableSessionInfo

Use PESetNthTableSessionInfo to set the specified session information when opening a Microsoft Access table. Many Microsoft Access database tables require that a session be opened before the table can be used. Use PESetNthTableSessionInfo to open the session when required.

C Syntax
BOOL CRPE_API PESetNthTableSessionInfo (

        short printJob,

        short tableN,

        PESessionInfo FAR *sessionInfo,

        BOOL propagateAcrossTables );
Parameters

printJob | Specifies the print job for which you want to change the MS Access session information.
tableN | Specifies the 0-based number of the table for which you want to open the session. The first table is table 0. The last table is N-1.
sessionInfo | Specifies a pointer to PESessionInfo.
propagateAcrossTables | Boolean value indicating whether the session information should be used for opening all tables being used in the report.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

In Microsoft Access 95 and later, an Access database can have session security (also known as user-level security), database-level security, or both.

  • If the Access database contains only session security, simply pass the session password to the Password member before calling PESetNthTableSessionInfo.
  • If the Access database contains database-level security, use a newline character, '\n' (ASCII character 10) followed by the database-level password (for example, "\ndbpassword").
      • If the Access database contains both session security and database-level security, use the session password followed by the newline character and the database password (for example, "sesspswd\ndbpassword").
  • Alternately, database-level security can also be handled by assigning the database-level password to the Password member of PELogOnInfo and calling PESetNthTableLogOnInfo.
VB Syntax
Declare Function PESetNthTableSessionInfo Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal TableN As Integer, _

    SessionInfo As PESessionInfo, ByVal PropagateAcrossTables _

    As Integer ) As Integer
Delphi Syntax
function PESetNthTableSessionInfo (

    printJob: Word;

    tableN: smallint;

    var sessionInfo: PESessionInfo;

    propagateAcrossTables: Bool

    ): Bool stdcall;


PESetParameterMinMaxValue

Use PESetParameterMinMaxValue to set the minimum and/or maximum possible values for the specified parameter in a report.

C Syntax
BOOL CRPE_API PESetParameterMinMaxValue(

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName,

        PEValueInfo FAR *valueMin,

        PEValueInfo FAR *valueMax );
Parameters

printJob | Specifies the print job for which you want to set minimum and/or maximum parameters values.
parameterFieldName | Specifies a pointer to the string containing the parameter name.
reportName | Specifies a pointer to the string containing the report name. See Remarks below.
valueMin | Specifies a pointer to PEValueInfo, which contains minimum value information. See Remarks below.
valueMax | Specifies a pointer to PEValueInfo, which contains maximum value information. See Remarks below.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Regarding parameter reportName:
      • For the main report, pass an empty string ("").
      • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
  • Regarding parameters valueMin and valueMax:
      • Set valueMin to NULL if specifying maximum value only; valueMin must be non NULL if valueMax is NULL.
      • Set valueMax to NULL if specifying minimum value only; valueMax must be non-NULL if valueMin is NULL.
      • If both valueMin and valueMax are specified (that is, non-NULL), then the valueType field of both structures must be the same or error code PE_ERR_INCONSISTANTTYPES is returned.
VB Syntax
Declare Function PESetParameterMinMaxValue Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, valueMin As PEValueInfo, _

    valueMax As PEValueInfo ) As Integer
Delphi Syntax
function PESetParameterMinMaxValue (

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar;

    var valueMin: PEValueInfo;

    var valueMax: PEValueInfo): BOOL stdcall;


PESetParameterPickListOption

Use PESetParameterPickListOption to set the parameter pick list options for a report. This function sets the values in PEParameterPickListOption.

C Syntax
BOOL CRPE_API PESetParameterPickListOption (

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportName,

        PEParameterPickListOption FAR *pickListOption );
Parameters

printJob | Specifies the print job for which you want to set the parameter pick list options.
parameterFieldName | Specifies a pointer to the parameterFieldName for which you want to set pick list options.
reportName | Specifies a pointer to the report name. See Remarks below.
pickListOption | Specifies a pointer to PEParameterPickListOption, which will contain the new information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax
Declare Function PESetParameterPickListOption Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, pickListOption As
PEParameterPickListOption _

    ) As Integer
Delphi Syntax
function PESetParameterPickListOption (

  printJob           : Smallint;

  parameterFieldName : PChar;

  reportName         : PChar;

  var pickListOption : PEParameterPickListOption): Bool; {$ifdef WIN32}

        stdcall; {$endif}


PESetParameterValueInfo

Use PESetParameterValueInfo to set information about the values which can be stored in a specified parameter field. For example, it establishes whether fields are editable, nullable, or can have multiple values, etc.

C Syntax
BOOL CRPE_API PESetParameterValueInfo(

        short printJob,

        const char FAR *parameterFieldName,

        const char FAR *reportname,

        PEParameterValueInfo FAR *valueInfo );
Parameters

printJob | Specifies the print job for which you want to set parameter value information.
parameterFieldName | Specifies a pointer to the string containing the parameter field name.
reportName | Specifies a pointer to the string containing the report name. See Remarks below.
valueInfo | Specifies a pointer to PEParameterValueInfo, which contains the parameter value information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Regarding parameter reportName:

  • For the main report, pass an empty string ("").
  • For a subreport, pass the file path and name of the subreport as a NULL-terminated string.
VB Syntax
Declare Function PESetParameterValueInfo Lib "crpe32.dll" ( _

    ByVal printJob As Integer, ByVal parameterFieldName As String, _

    ByVal reportName As String, valueInfo As PEParameterValueInfo ) As
Integer
Delphi Syntax
function PESetParameterValueInfo (

    printJob: smallint;

    const parameterFieldName: PChar;

    const reportName: PChar;

    var valueInfo: PEParameterValueInfo

    ): BOOL stdcall;


PESetPrintDate

Use PESetPrintDate to set a print date that may be different than the system calendar date. Use this function any time you want to show a print date (or use a print date in formulas) other than the actual date of printing.

C Syntax
BOOL CRPE_API PESetPrintDate (

        short printJob,

        short year,

        short month,

        short day );
Parameters

printJob | Specifies the print job for which you want to set the print date.
year | Specifies the year component of the print date. Enter a 4 digit year value (1994, 1993, etc.).
month | Specifies the month component of the print date. Months are numbered from 1 to 12, where January = 1 and December = 12. To use July as the print month, for example, you would enter the value 7.
day | Specifies the day component of the print date. Enter the actual day of the month you want to use (7, 18, 28, etc.).

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • You change the print date, typically, when you want to run the report today yet have it appear to have been run on a different date. An example would be, if you were out of town on the last day of the previous month and you later want to run a report for that month and make it appear as if it were run on the last day of the month.
  • This function should be called before PEStartPrintJob, or the results may be inconsistent or unexpected.
VB Syntax

VB Sample Code for modifying title, options, margins, and date

Declare Function PESetPrintDate Lib "crpe32.dll" (ByVal printJob As
Integer, ByVal Date_Year As Integer, ByVal Date_Month As Integer, ByVal
Date_Day As Integer) As Integer
Delphi Syntax
function PESetPrintDate (

    printJob: Word;

    year: smallint;

    month: smallint;

    day: smallint

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PESetPrintDate (CWORD, CWORD, CWORD, CWORD) CRPE.DLL


PESetPrintOptions

Use PESetPrintOptions to set the print options for the report to the values supplied in PEPrintOptions. Use this function any time you want to set the starting page number, the ending page number, the number of report copies, and/or collation instructions for a print job in response to user specifications at runtime.

C Syntax
BOOL CRPE_API PESetPrintOptions (

    short printJob,

    PEPrintOptions FAR *options );
Parameters

printJob | Specifies the print job for which you want to set printing options.
options | Specifies a pointer to PEPrintOptions. If this parameter is set to 0 (NULL), the function prompts the user for these options. Using this, you can get the behavior of the print-to-printer button in the preview window by calling PESetPrintOptions with a NULL pointer and then calling PEPrintWindow.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for modifying title, options, margins, and date

Declare Function PESetPrintOptions Lib "crpe32.dll" (ByVal printJob As
Integer, Options As PEPrintOptions) As Integer
Delphi Syntax

Delphi code for getting/setting print options

function PESetPrintOptions (

    printJob: Word;

    var options: PEPrintOptions

    ): Bool stdcall;


PESetReportOptions

Use PESetReportOptions to set various options for the report to the values supplied in PEReportAlertInfo. Use this function any time you want to set any of the report options found in the Report|Options dialog box in the Crystal Reports Designer.

C Syntax
BOOL CRPE_API PESetReportOptions (

        short printJob,

        PEReportOptions FAR *reportOptions );
Parameters

printJob | Specifies the print job for which you want to set report options.
reportOptions | Specifies a pointer to PEReportAlertInfo.

Returns
  • TRUE if the call is successful
  • FALSE if the call fails.
VB Syntax
Declare Function PESetReportOptions Lib "crpe32.dll" (ByVal printJob _

        As Integer, reportOptions As PEReportOptions) As Integer
Delphi Syntax
function PESetReportOptions (

    printJob: smallint;

    var reportOptions: PEReportOptions

    ): Bool stdcall;


PESetReportSummaryInfo

Use PESetReportSummaryInfo to set report summary information. Report summary information corresponds to the Summary Info dialog box found in Crystal Reports.

C Syntax
BOOL CRPE_API PESetReportSummaryInfo (

        short printJob,

        PEReportSummaryInfo FAR *summaryInfo );
Parameters

printJob | Specifies the print job for which you want to set summary information.
summaryInfo | Specifies the pointer to PEReportSummaryInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

This function should be called before PEStartPrintJob, or the results may be inconsistent or unexpected.

VB Syntax
Declare Function PESetReportSummaryInfo Lib "crpe32.dll" (

    ByVal printJob as Integer, summaryInfo as PEReportSummaryInfo ) as
Integer
Delphi Syntax
function PESetReportSummaryInfo (

    printJob: Word;

    var summaryInfo: PEReportSummaryInfo

    ): Bool; stdcall


PESetReportTitle

Use PESetReportTitle to change the report title in the report summary information. This function can also be used as one of a series of functions: PEGetReportTitle; PEGetHandleString; or REFSetReportTitle). This series can be used in a Custom-Print Link to identify and then change an existing report title in response to a user selection at print time.

C Syntax
BOOL CRPE_API PESetReportTitle (

        short printJob,

        const char FAR *title );
Parameters

printJob | Specifies the print job for which you want to set the report title.
title | Specifies a pointer to the null-terminated string containing the new title that you want to assign to the report.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • When you give the user the ability to change the report title at print time, your link must include code to replace text with a user-generated value.
  • This function should be called before PEStartPrintJob, or the results may be inconsistent or unexpected.
VB Syntax

VB Sample Code for modifying title, options, margins, and date

Declare Function PESetReportTitle Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal Title As String ) As Integer
Delphi Syntax
function PESetReportTitle (

    printJob: Word;

    title: PChar

    ): Bool stdcall;
dBASE for Windows Syntax
EXTERN CLOGICAL PESetReportTitle (CWORD, CSTRING) CRPE.DLL


PESetSectionFormat

Use PESetSectionFormat to set the section format settings for selected sections in the specified report to the values in PESectionOptions. This function can be used to provide specialized formatting for printing invoices, form letters, printing to pre-printed forms, etc. It allows you to hide a section, insert a page break either before or after a section begins, reset the page number to 1 after a group value prints, prevent page breaks from spreading data from a single record over two pages, and to print group values only at the bottom of a page.

C Syntax
BOOL CRPE_API PESetSectionFormat (

        short printJob,

        short sectionCode,

        PESectionOptions FAR *options );
Parameters

printJob | Specifies the print job for which you want to set section formatting options.
sectionCode | Specifies the Section Codes for the report section(s) for which you want to set formatting options. See Working with section codes.
options | Specifies a pointer to PESectionOptions. Use this structure to set your section options.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • There can be multiple sections in an area.
  • This function should be called before PEStartPrintJob or the results may be inconsistent or unexpected.
VB Syntax

VB Sample Code for modifying sections and lines

Declare Function PESetSectionFormat Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionCode As Integer,

    Options As PESectionOptions ) As Integer
Delphi Syntax

Delphi code for getting/setting section format

function PESetSectionFormat (

    printJob: Word;

    sectionCode: smallint;

    var options: PESectionOptions

    ): Bool stdcall;


PESetSectionFormatFormula

Use PESetSectionFormatFormula to change the specified section format formula to the formula string you supply as a parameter. This function will only change the text of a formula which already exists in the report; you cannot use it to add a formula. When you give the user the ability to change the formula at print time, your link must include code to replace the formulaString parameter with a user-generated value.

C Syntax
BOOL CRPE_API PESetSectionFormatFormula (

        short printJob,

        short sectionCode,

        short formulaName,

        const char FAR *formulaString );
Parameters

printJob | Specifies the print job for which you want to set a new selection formula string.
sectionCode | Specifies the Section Codes, for the report section(s) for which you want to set formatting options. See Working with section codes.
formulaName | Specifies the name of the formatting formula for which you want to supply a new string. Use one of the PE_FFN_XXX Area/Section Format Formula Constants.
formulaString | Specifies a pointer to the null-terminated string that you want to assign to the format formula.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
  • Error code PE_ERR_BADFORMULANAME if the formula does not exist.
  • Error code PE_ERR_BADFORMULATEXT if there is an error in the formula.
Remarks
  • This function should be called before PEStartPrintJob, or the results may be inconsistent or unexpected.
  • Not all formula names can be applied to all sections.
VB Syntax
Declare Function PESetSectionFormatFormula Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionCode As Integer,

    ByVal formulaName As Integer, ByVal FormulaString As String ) As
Integer
Delphi Syntax
function PESetSectionFormatFormula (

    printJob: Word;

    sectionCode: smallint;

    formulaName: smallint;

    formulaString: PChar

    ): Bool stdcall;


PESetSectionHeight

Use PESetSectionHeight to set the section height information for the specified section. This is the replacement API Call for PESetMinimumSectionHeight and should be used for all new development.

C Syntax
BOOL CRPE_API PESetSectionHeight(

        short printJob,

        short sectionCode,

        short height );
Parameters

printJob | Specifies the print job for which you want to set section height information.
sectionCode | Specifies the Section Codes for the section(s) for which you want to set section height information. See Working with section codes.
height | The section height measured in twips.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PESetSectionHeight Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal sectionCode As Integer,

    ByVal height As Integer ) As Integer
Delphi Syntax
function PESetSectionHeight (

    printJob: Smallint;

    sectionCode:     Smallint;

    Height: Smallint (*in twips*)

    ): Bool stdcall;


PESetSelectionFormula

Use PESetSelectionFormula to change the selection formula to the formula string that you supply as a parameter. This function can be used by itself to replace a known record selection formula and also as one of a series of functions: PEGetSelectionFormula; PEGetHandleString; or PESetSelectionFormula). The series can be used in a Custom-Print link to identify and then change an existing record selection formula at print time in response to a user selection. When you give the user the ability to change the record selection formula at print time, your link must include code to replace formulaString with a user-generated value.

C Syntax
BOOL CRPE_API PESetSelectionFormula (

        short printJob,

        const char FAR *formulaString );
Parameters

printJob | Specifies the print job for which you want to set a new selection formula string.
formulaString | Specifies a pointer to the null-terminated string that you want to assign to the selection formula.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails due to an internal error (for example, the connection to the database fails).
Remarks
  • Immediately after setting the new formula with PESetSelectionFormula, the new formula should be verified with PECheckSelectionFormula.
  • This function should be called before PEStartPrintJob or the results may be inconsistent or unexpected.
VB Syntax

VB Sample Code for modifying selection formulas and group selection formulas

Declare Function PESetSelectionFormula Lib "crpe32.dll" (ByVal printJob
As Integer, ByVal FormulaString As String) As Integer
Delphi Syntax
function PESetSelectionFormula (

    printJob: Word;

    formulaString: PChar

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PESetSelectionFormula (CWORD, CSTRING) CRPE.DLL


PESetSQLExpression

Use PESetSQLExpression to enter an SQL expression for a specified report.

C Syntax
BOOL CRPE_API PESetSQLExpression (

        short printJob,

        const char FAR *expressionName,

        const char FAR *expressionString );
Parameters

printJob | Specifies the print job for which you want to set an SQL expression.
expressionName | Specifies a pointer to the string containing the expression name.
expressionString | Specifies a pointer to the string containing the SQL expression.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PESetSQLExpression Lib "crpe32.dll" (ByVal printJob As
Integer, ByVal expressionName As String, ByVal expressionString As
String) As Integer
Delphi Syntax
function PESetSQLExpression (

    printJob: Smallint;

    const expressionName: PChar;

    const expressionString: PChar

    ): Bool stdcall;


PESetSQLQuery

Use PESetSQLQuery to change the SQL query to the query string you supply as a parameter. Use this function to update the SQL query that will be used to print the specified report, typically to add optimizations to the WHERE clause.

C Syntax
BOOL CRPE_API PESetSQLQuery (

        short printJob,

        const char FAR *queryString );
Parameters

printJob | Specifies the print job for which you want to modify the SQL query.
queryString | Specifies a pointer to the null-terminated string that you want to use to replace the existing SQL query.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • This function is useful for reports with SQL queries that were explicitly edited in the Show SQL Query dialog box in Crystal Reports (that is, those reports that needed database-specific selection criteria or joins). Otherwise it is usually best to continue using function calls such as PESetSelectionFormula, and let Crystal Reports build the SQL query automatically.
  • PESetSQLQuery has the same restrictions as editing in the Show SQL Query dialog box. In particular, changes are accepted in the WHERE and ORDER BY clauses but they are ignored in the SELECT list
    of fields.
  • This call only applies to reports created against an ODBC source or on a native SQL database connection.
VB Syntax

VB Sample Code for modifying SQL statements

Declare Function PESetSQLQuery Lib "crpe32.dll" ( ByVal printJob As Integer, ByVal QueryString As String ) As Integer

Delphi Syntax

Delphi code for getting/setting the SQL query

function PESetSQLQuery (

    printJob: Word;

    queryString: PChar

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PESetSQLQuery (CWORD, CSTRING) CRPE.DLL


PESetTrackCursorInfo

Use PESetTrackCursorInfo to set information for tracking the position of the mouse cursor over the preview window. This functions is only valid if the report was sent to a preview window (see PEOutputToWindow), and if events for the preview window have been enabled (see PEEnableEvent).

C Syntax
BOOL CRPE_API PESetTrackCursorInfo (

        short printJob,

        PETrackCursorInfo FAR *cursorInfo );
Parameters

printJob | Specifies the print job for which you want to track the mouse cursor.
cursorInfo | Specifies a pointer to PETrackCursorInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • By default, all area's track cursors are arrow cursors. If the preview window contains a drill-down field (database field, summary, group name, group graph), the group area will use a magnify cursor. Group graphs in other areas will also use the magnify cursor.
  • This function can be used to give the user visual feed back especially when tracking events.
VB Syntax
Declare Function PESetTrackCursorInfo Lib "crpe.dll" (ByVal printJob As
Integer, cursorInfo As PETrackCursorInfo) As Integer
Delphi Syntax
function PESetTrackCursorInfo(

    printJob: smallint;

    var cursorInfo: PETrackCursorInfo

    ): smallint stdcall;


PESetWindowOptions

Use PESetWindowOptions to set display options for the preview window, including which preview window controls are available. This function must be called after PEOutputToWindow.

C Syntax
BOOL CRPE_API PESetWindowOptions (

        short printJob,

        PEWindowOptions FAR *options );
Parameters

printJob | Specifies the print job for which you want to set preview window display options.
options | Specifies a pointer to a PEWindowOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PESetWindowOptions Lib "crpe.dll" (

    ByVal printJob As Integer, Options As PEWindowOptions ) As Integer
Delphi Syntax
function PESetWindowOptions (

    printJob: Word;

    var options: PEWindowOptions

    ): Bool stdcall;


PEShow...Page

Use the PEShow...Page function calls to display the specified page in the preview window. Use these functions any time you want to display specific pages of a report in the preview window or give the user the ability to move forward, backward, or to a specified page in a report in the preview window. Use PEGetNPages, to determine the number of pages available in the specified report when using PEShowNthPage, for example.

C Syntax
BOOL CRPE_API PEShowFirstPage (

        short printJob );
BOOL CRPE_API PEShowLastPage (

        short printJob );
BOOL CRPE_API PEShowNextPage (

        short printJob );
BOOL CRPE_API PEShowNthPage (

        short printJob,

        short pageN );
BOOL CRPE_API PEShowPreviousPage (

        short printJob );
Parameter(s)

printJob

Specifies the print job for which you want to indicate the page to be displayed.

  • The following parameter applies only to PEShowNthPage.

    pageN

    Specifies the 1-based number indicating the report page that you want to display when calling PEShowNthPage. See Remarks below.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Using PEGetJobStatus, you can determine how many pages are contained in the specified report. This information will determine the range available for parameter pageN when using PEShowNthPage.

VB Syntax

VB Sample Code for Previewing a Report

Declare Function PEShowFirstPage Lib "crpe32.dll" (

    ByVal printJob As Integer ) As Integer
Declare Function PEShowLastPage Lib "crpe32.dll" (

    ByVal printJob As Integer ) As Integer
Declare Function PEShowNextPage Lib "crpe32.dll" (

    ByVal printJob As Integer ) As Integer
Declare Function PEShowNthPage Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal pageN As Integer ) As Integer
Declare Function PEShowPreviousPage Lib "crpe32.dll" (

    ByVal printJob As Integer ) As Integer
Delphi Syntax
function PEShowFirstPage (

    printJob: Word

    ): Bool stdcall;
function PEShowLastPage (

    printJob: Word

    ): Bool stdcall;
function PEShowNextPage (

    printJob: Word

    ): Bool stdcall;
function PEShowPreviousPage (

    printJob: Word

    ): Bool stdcall;
function PEShowNthPage (

    printJob: Word;

    pageN: Smallint

    ): Bool stdcall;
dBASE for Windows Syntax
EXTERN CLOGICAL PEShowNextPage (CWORD) CRPE.DLL
EXTERN CLOGICAL PEShowFirstPage (CWORD) CRPE.DLL
EXTERN CLOGICAL PEShowPreviousPage (CWORD) CRPE.DLL
EXTERN CLOGICAL PEShowLastPage (CWORD) CRPE.DLL


PEShowPrintControls

Use PEShowPrintControls to display the print controls (First, Previous, Next, and Last Page buttons as well as the buttons for Cancel, Close, Export, and Print to Printer). Use this call any time you want to provide control over whether print controls are displayed or not.

C Syntax
BOOL CRPE_API PEShowPrintControls (

        short printJob,

        BOOL showPrintControls );
Parameters

printJob | Specifies the print job for which you want to toggle the display of print controls.
showPrint Controls | Boolean value indicates whether or not the print controls are displayed. TRUE will cause the print controls to be displayed; FALSE will hide the print controls.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

Print controls are displayed by default. It is not necessary to use this function simply to display controls but only if you want the user to control whether or not the controls are visible.

VB Syntax

VB Sample Code for Previewing a Report

Declare Function PEShowPrintControls Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal ShowPrintControls As Integer ) As
Integer
Delphi Syntax
function PEShowPrintControls (

    printJob: Word;

    showPrintControls: Bool

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PEShowPrintControls (CWORD, CLOGICAL) CRPE.DLL


PEStartPrintJob

Use PEStartPrintJob to start the printing of a report. This function is used as a mandatory part of each Custom-Print Link to trigger the printing of a report to the printer or to the preview window.

C Syntax
BOOL CRPE_API PEStartPrintJob (

        short printJob,

        BOOL waitUntilDone );
Parameters

printJob | Specifies the print job you want to start.
waitUntilDone | BOOL. Reserved. This parameter must always be set to TRUE.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

A print job can be started only once. Once started, the only function that can be used is PEClosePrintJob.

VB Syntax

VB Sample Code for Custom Print Link

Declare Function PEStartPrintJob Lib "crpe32.dll" (ByVal printJob _

        As Integer, ByVal WaitOrNot As Integer) As Integer
Delphi Syntax

Delphi code for exporting a report

function PEStartPrintJob (

    printJob: Word;

    waitUntilDone: Bool

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PEStartPrintJob (CWORD, CLOGICAL) CRPE.DLL


PETestNthTableConnectivity

Use PETestNthTableConnectivity to test whether a database table's settings are valid and ready to be reported on. This function is typically used if you plan to print at a later time but you want to test now to make sure everything is in order for logging on. For example, your application can prompt your user for a password and then test it before printing begins. See Remarks below.

C Syntax
BOOL CRPE_API PETestNthTableConnectivity (

        short printJob,

        short tableN );
Parameters

printJob | Specifies the print job for which you want to test a table's connection settings.
tableN | Specifies the 0-based number of the table for which you want to test the database table settings. The first table is table 0. The last table is N-1.

Returns
  • TRUE if the database session, log on, and location information is all correct.
  • FALSE if the call fails.
Remarks
  • This function may require a significant amount of time to complete, since it will first open a user session (if required), then log on to the database server (if required), and then open the appropriate database table (to test that it exists).
  • PETestNthTableConnectivity does not read any data.
  • PETestNthTableConnectivity closes the table immediately once the connection has been tested successfully.
  • If the connection fails at one of the following steps, the error code set indicates which function needs to be called to provide updated database information.

    Connection Failure Error Code Update with Function

    Unable to begin a session.

    PE_ERR_DATABASESESSION

    PESetNthTableSessionInfo

    Unable to log on to a server.

    PE_ERR_DATABASELOGON

    PESetNthTableLogOnInfo

    Unable to open the table.

    PE_ERR_DATABASELOCATION

    PESetNthTableLocation

  • Logging off is performed when the print job is closed.
VB Syntax

VB Sample Code for modifying database table settings

Declare Function PETestNthTableConnectivity Lib "crpe32.dll" ( ByVal
printJob As Integer, ByVal TableN As Integer ) As Integer
Delphi Syntax

Delphi code for getting/setting logon information

function PETestNthTableConnectivity (

    printJob: Word;

    tableN: smallint

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PETestNthTableConnectivity (CWORD, CWORD) CRPE.DLL


PEVerifyDatabase

Use PEVerifyDatabase to verify that a connection to the database(s) specified in a report are valid.

C Syntax
BOOL CRPE_API PEVerifyDatabase (

        short printJob );
Parameter

printJob

Specifies the print job for which you want to verify the database connection.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax
Declare Function PEVerifyDatabase Lib "crpe32.dll" (

    ByVal printJob As Integer ) As Integer
Delphi Syntax
function PEVerifyDatabase

    printJob: smallint

    ): Bool stdcall;


PEZoomPreviewWindow

Use PEZoomPreviewWindow to change the magnification of the preview window to a specified level. Use this function when the report has been printed to a preview window and you want to set the magnification of the preview window to a specific level (Full Page, Fit One Side, Fit Both Sides, or a specified level).

C Syntax
BOOL CRPE_API PEZoomPreviewWindow (

        short printJob,

        short level );
Parameters

printJob | Specifies the print job for which you want to set the magnification level in the preview window.
level | The zoom level at which you want to set the preview window. This value can be a set to a specific magnification level (%) in the range from 25 to 400, or you can use one of the Zoom Level Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
VB Syntax

VB Sample Code for Previewing a Report

Declare Function PEZoomPreviewWindow Lib "crpe32.dll" (

    ByVal printJob As Integer, ByVal ZoomLevel As Integer ) As Integer
Delphi Syntax
function PEZoomPreviewWindow (

    printJob: Word;

    level: smallint

    ): Bool stdcall;
dBASE for Windows Syntax

EXTERN CLOGICAL PEZoomPreviewWindow (CWORD, CWORD)CRPE.DLL


Print Engine Structures

The print Engine structures are listed alphabetically in this section.

  • PEAlertInstanceInfo
  • PECloseButtonClickedEventInfo
  • PEDrillOnDetailEventInfo
  • PEDrillOnGroupEventInfo
  • PEEnableEventInfo
  • PEExportOptions
  • PEFieldMappingEventInfo
  • PEFieldValueInfo
  • PEFontColorInfo
  • PEFormulaSyntax
  • PEGeneralPrintWindowEventInfo
  • PEGraphAxisInfo
  • PEGraphOptionInfo
  • PEGraphTypeInfo
  • PEGroupOptions
  • PEGroupTreeButtonClickedEventInfo
  • PEHyperlinkEventInfo
  • PEJobInfo
  • PELaunchSeagateAnalysisEventInfo
  • PELogOnInfo
  • PEMouseClickEventInfo
  • PEObjectInfo
  • PEParameterFieldInfo
  • PEParameterPickListOption
  • PEParameterValueInfo
  • PEPrintOptions
  • PEReadingRecordsEventInfo
  • PEReportFieldMappingInfo
  • PEReportAlertInfo
  • PEReportOptions
  • PEReportSummaryInfo
  • PESearchButtonClickedEventInfo
  • PESectionOptions
  • PESessionInfo
  • PEShowGroupEventInfo
  • PEStartEventInfo
  • PEStopEventInfo
  • PESubreportInfo
  • PETableDifferenceInfo
  • PETablePrivateInfo
  • PETableType
  • PETrackCursorInfo
  • PEValueInfo
  • PEVersionInfo
  • PEWindowOptions
  • PEZoomLevelChangingEventInfo
  • UXDDiskOptions
  • UXDMAPIOptions
  • UXDSMIOptions
  • UXDPostFolderOptions
  • UXDVIMOptions
  • UXFCharSeparatedOptions
  • UXFCommaTabSeparatedOptions
  • UXFDIFOptions
  • UXFHTML3Options
  • UXFODBCOptions
  • UXFPaginatedTextOptions
  • UXFRecordStyleOptions


PEAlertInstanceInfo

PEAlertInstanceInfo contains information for a selected instance of a Report Alert. This information is used by PEGetNthAlertInstanceInfo, to retrieve information on the selected instance of the Report Alert.

C Syntax
typedef struct PEAlertInstanceInfo
{
    WORD StructSize;
    short alertMessageLength;
    HANDLE alertMessage;
} PEAlertInstanceInfo;
Members

StructSize | Specifies the size of the PEAlertInstanceInfo structure. Initialize this member to PE_SIZEOF_ALERT_INSTANCE_INFO.
alsertMessage Length | Specifies the length of the alert message generated for this instance of the Report Alert.
alertMessage | Specifies a handle to the string containing alert message generated for this instance of the Report Alert.

Remarks

In the present build only the first instance of the Report Alert is created at runtime. This limitation will be addressed in a future release.

VB Type Listing
Type PEAlertInstanceInfo

    StructSize As Integer

    alertMessageLength As Integer

    alertMessage As Long

End Type
Delphi Record Listing
type PEAlertInstanceInfo = record
    StructSize : Word;
    alertMessageLength : Smallint;
    alertMessage : HWND;
end;


PECloseButtonClickedEventInfo

This structure contains information about a close button clicked event. When the close button in a preview window is clicked, a callback function will be called with EventId = PE_CLOSE_BUTTON_CLICKED_EVENT.

C Syntax
typedef struct PECloseButtonClickedEventInfo {

    WORD StructSize;

    WORD viewIndex;

    long windowHandle;

} PECloseButtonClickedEventInfo;
Members

StructSize | Specifies the size of the PECloseButtonClickedEventInfo structure. Initialize this number to PE_SIZEOF_CLOSE_BUTTON_CLICKED_EVENT_INFO.
viewIndex | Specifies the 0-based index number indicating which view is going to be closed.
windowHandle | Specifies the handle for the frame window on which the button is placed.

VB Type Listing
Type PECloseButtonClickedEventInfo

    StructSize As Integer

    viewIndex As Integer

    windowHandle As Long

End Type
Delphi Record Listing
type

    PECloseButtonClickedEventInfo = record

        StructSize: Word;

        viewIndex: Word;

        windowHandle: HWnd;

    end;


PEDrillOnDetailEventInfo

PEDrillOnDetailEventInfo contains information related to callback Event Id = PE_DRILL_ON_DETAIL_EVENT event information.

C Syntax
typedef struct PEDrillOnDetailEventInfo {

    WORD StructSize;

    short selectedFieldIndex;

    long windowHandle;

    struct PEFieldValueInfo **fieldValueList;

    short nFieldValue;

} PEDrillOnDetailEventInfo;
Members

StructSize | Specifies the size of the PEDrillOnDetailEventInfo structure. Initialize this number to PE_SIZEOF_DRILL_ON_DETAIL_EVENT_INFO.
selectedFieldIndex | The 0-based index indicating which drill-down field was selected. Contains -1 if no field was selected.
windowHandle | Frame window handle where the drill on detail event happens.
fieldValueList | Points to an array of PEFieldValue. Memory pointed by fieldValueList is freed after calling the callback function.
nFieldValue | The 1-based index of the value in field value list (for example, if the value is listed second, the number would be 2).

Remarks

If the user clicks one of the fields in the Details section, selectedFieldIndex will point to the field index in fieldValueList. These fields have to be one of database field, group name field, summary field, formula field. Clicks on text object, graph, picture, ole, subreport, special var field, or database memo or blob field, selectedFieldIndex return -1.

Delphi Record Listing
type

    PEFieldValueInfoDoublePtr = ^PEFieldValueInfoPtr

    PEDrillOnDetailEventInfo = record{

        StructSize: Word;

        selectedFieldIndex:smallint;

        windowHandle: longint;

        fieldValueList: PEFieldValueInfoDoublePtr;

        nFieldValue: smallint;

    end;


PEDrillOnGroupEventInfo

PEDrillOnGroupEventInfo specifies drill on group information when PE_DRILL_ON_GROUP_EVENT happens.

C Syntax
typedef struct PEDrillOnGroupEventInfo {

    WORD StructSize;

    WORD drillType;

    long windowHandle;

    char **groupList;

    WORD groupLevel;

} PEDrillOnGroupEventInfo;
Members

StructSize | Specifies the size of the PEDrillOnGroupEventInfo structure. Initialize this number to PE_SIZEOF_DRILL_ON_GROUP_EVENT_INFO.
drillType | Specifies the type of drill down that is used. Use one of the following values.
 | Constant | Description
 | PE_DE_ON_GROUP | Drill-down on a group summary or subtotal.
 | PE_DE_ON_GROUPTREE | Drill-down a Group Tree node.
 | PE_DE_ON_GRAPH | Drill-down a group graph object.
 | PE_DE_ON_MAP | Drill-down on a map region.
 | PE_DE_ON_SUBREPORT | Drill-down on a subreport.
windowHandle | Frame window handle where the event happens.
groupList | Specifies an array of pointers to group names in the report when drilling on a group summary, a Group Tree, a chart, or a map; and a pointer to a single element array containing the subreport name when drilling on a subreport. This memory is freed after the callback function is called.
groupLevel | The number of the group name in the group list.

Remarks

Member groupList will be freed after the callback function. You will need to make a copy of the groupList if you want to use it later.

VB Type Listing
Type PEDrillOnGroupEventInfo

    StructSize As Integer

    drillType As Integer

    windowHandle As Long

    groupList As String

    groupLevel As Integer

End Type
Delphi Record Listing
type

    PEPCharPointer = ^PChar

    PEDrillOnGroupEventInfo

        StructSize: Word;

        drillType: Word;

        windowHandle: HWnd;

        groupList: PEPCharPointer;

        groupLevel: Word;

    end;


PEEnableEventInfo

Events are grouped in CRPE. PEEnableEventInfo specifies which group event is enabled or disabled. All events are disabled by default. Use PEEnableEvent, to enable events.

C Syntax
typedef struct PEEnableEventInfo {

    WORD StructSize;

    short startStopEvent;

    short readingRecordEvent;

    short printWindowButtonEvent;

    short drillEvent;

    short closePrintWindowEvent;

    short activatePrintWindowEvent;

    short fieldMappingEvent;

    short mouseClickEvent;

    short hyperlinkEvent;

    short launchSeagateAnalysisEvent;

} PEEnableEventInfo;
Members

Each member of type short can be set to TRUE, FALSE, or PE_UNCHANGED for no change.

StructSize | Specifies the size of the PEEnableEventInfo structure. Initialize this number to PE_SIZEOF_ENABLE_EVENT_INFO.
startStopEvent | Boolean value, or PE_UNCHANGED for no change. Start/Stop event.
readingRecordEvent | Boolean value, or PE_UNCHANGED for no change. Reading record event.
printWindowButton Event | Boolean value, or PE_UNCHANGED for no change. Print window button event.
drillEvent | Boolean value, or PE_UNCHANGED for no change. Drill event.
closePrintWindowEvent | Boolean value, or PE_UNCHANGED for no change. Close print window event.
activatePrintWindow Event | Boolean value, or PE_UNCHANGED for no change. Activate print window event.
fieldMappingEvent | Boolean value, or PE_UNCHANGED for no change. Field mapping event.
mouseClickEvent | Boolean value, or PE_UNCHANGED for no change. Mouse click event.
hyperlinkEvent | Boolean value, or PE_UNCHANGED for no change. Hyperlink event.
launchSeagateAnalysis Event | Boolean value, or PE_UNCHANGED for no change. Launch Seagate Analysis event. Note: Seagate Analysis is now known as Crystal Analysis.

Remarks
  • By default, all events are disabled. Use PEEnableEvent, to enable the desired event.
  • For startStopEvent, readingRecordEvent, printWindowEvent, drillEvent, closePrintWindowEvent, and activatePrintWindowEvent, use PE_UNCHANGED for no change.
VB Type Listing
Type PEEnableEventInfo

    StructSize As Integer

    startStopEngine As Integer

    readingRecordEvent As Integer

    printWindowButtonEvent As Integer

    drillEvent As Integer

    closePrintWindowEvent As Integer

    activatePrintWindowEvent As Integer

    fieldMappingEvent As Integer

    mouseClickEvent As Integer

End Type
Delphi Record Listing
type

    PEEnableEventInfo = record

        StructSize: Word;

        startStopEvent: smallint;

        readingRecordEvent: smallint;

        printWindowButtonEvent: smallint;

        drillEvent: smallint;

        closePrintWindowEvent: smallint;

        activatePrintWindowEvent: smallint;

        fieldMappingEvent: smallint;

        mouseClickEvent: smallint;

    end;


PEExportOptions

PEExportOptions contains file format and output destination information that is retrieved by PEGetExportOptions, and used PEExportTo, when exporting reports.

C Syntax
typedef struct PEExportOptions {

    WORD StructSize;

    char formatDLLName [PE_DLL_NAME_LEN];

    DWORD formatType;

    void FAR *formatOptions;

    char destinationDLLName [PE_DLL_NAME_LEN];

    DWORD destinationType;

    void FAR *destinationOptions;

    WORD nFormatOptionsBytes;

    WORD nDestinationOptionsBytes;

} PEExportOptions;
Members

Visual Basic developers should refer to the VB syntax for specifics of the VB structure.

StructSize | Specifies the size of the PEExportOptions structure. Initialize the member to PE_SIZEOF_EXPORT_OPTIONS.
formatDLLName | Specifies a pointer to the null-terminated string that contains the format DLL name (of length PE_DLL_NAME_LEN = 64). The DLL is selected based on the format in which you want to export your report. Select the appropriate DLL name from the table below.
 | To export in this format | Use this DLL
 | Crystal Reports Format | u2fcr.dll
 | Data Interchange Format | u2fwordw.dll
formatType | Specifies the type of format you want to use from those types supported by the selected DLL. Whether the format DLL you select supports only one format type (for example, uxfcr.dll) or multiple format types (for example, uxfdoc.dll), you must still fill in this member. Select the format type you want to use from the table below.
 | To export a report in this format | Use this formatType
 | Crystal Reports Format | UXFCrystalReportType
 | Data Interchange Format | UXFDIFType
 | Word for Windows Format | UXFWordWinType
 | Word for DOS Format | UXFWordDosType
 | WordPerfect Format | UXFWordPerfectType
 | Quattro Pro 5.0 (WB1) Format | UXFQP5Type
 | Record Style Format (column of values) | UXFRecordType
 | Rich Text Format | UXFRichTextFormatType
 | Comma Separated Values Format (CSV) | UXFCommaSeparatedType
 | Tab Separated Values Format | UXFTabSeparatedType
 | Character Separated Values Format | UXFCharSeparatedType
 | Text Format (ASCII) | UXFTextType
 | Paginated Text Format (ASCII) | UXFPaginatedTextType
 | Tab Separated Text Format | UXFTabbedTextType
 | Lotus 1-2-3 (WK3) | UXFLotusWk3Type
 | Excel 4.0 | UXFXls4Type
 | Excel 5.0 | UXFXls5Type
 | Excel 5.0 Tabular | UXFXlsTypeTab
 | ODBC | UXFODBCType
 | HTML | UXFHTML3Type
 | Microsoft Internet Explorer 2 HTML | UXFExplorer2Type
 | Netscape 2 HTML | UXFNetscape2Type
formatOptions | Specifies a pointer to a structure that supplies date and number information. This information is used by the PEExportOptions structure when you want to export in one of the formats that support date and number options and you want to hard code your options. Select the appropriate structure (if needed) from the table below. WARNING: This member must be pointing to a valid address until PEStartPrintJob, is called.
 | To export a report in this format | Use this structure if you want to hard code formatOptions
 | Data Interchange Format | UXFDIFOptions
 | Record Style Format (column of values) | UXFRecordStyleOptions
 | Comma Separated Values (CSV) | UXFCommaTabSeparatedOptions
 | Tab Separated Values | UXFCommaTabSeparatedOptions
 | Character Separated Values | UXFCharSeparatedOptions
 | Paginated Text | UXFPaginatedTextOptions
 | Excel (Tabular) |
 | ODBC Format | UXFODBCOptions
 | HTML Format | UXFHTML3Options
destinationDLL Name | Specifies a pointer to the string (of length PE_DLL_NAME_LEN = 64, NULL-terminated) that contains the destination DLL name. The DLL used is determined by the destination to which you want to export your report. Select the appropriate DLL name from the table below.
To export a report to this destination | Use this DLL name | Use this DLL name
Disk File | uxddisk.dll | u2ddisk.dll
E-Mail (MAPI) | uxdmapi.dll | u2dmapi.dll
E-Mail (VIM) | uxdvim.dll | u2dvim.dll
Microsoft Exchange | uxdpost.dll | u2dpost.dll
destinationType | Specifies the type of destination you want to use from those types supported by the selected DLL. Even if the destinationDLL name you select supports only one destination type, you must still fill in this member. Select the destination type you want to use from the table below.
 | To export a report to this destination | Use this destinationType
 | Disk File | UXDDiskType
 | E-Mail (MAPI) | UXDMAPIType
 | E-Mail (VIM) | UXDVIMType
 | Microsoft Exchange | UXDExchFolderType
destination Options | Specifies a pointer to a structure containing information used by the PEExportOptions structure. This information is needed to export a report and hard code the file name (when exporting to Disk File) or e-mail message information (when exporting to MAPI or VIM destination). Select the appropriate structure (if needed) from the table below. WARNING: This member must be pointing to a valid address until PEStartPrintJob, is called.
 | To export a report to this destination | Use this structure if you want to hard code destinationOptions
 | Disk File | UXDDiskOptions
 | E-Mail (MAPI) | UXDMAPIOptions
 | E-Mail (VIM) | UXDVIMOptions
 | Microsoft Exchange | UXDPostFolderOptions
nFormat OptionsBytes | Set by PEGetExportOptions, and ignored by PEExportTo.
nDestination Options-Bytes | Set by PEGetExportOptions, and ignored by PEExportTo.

Remarks

Note that both the formatOptions and destinationOptions members must be pointing to a valid address until PEStartPrintJob, is called.

VB Type Listing
Type PEExportOptions

    StructSize As Integer

    FormatDLLName As String * PE_DLL_NAME_LEN

    FormatType1 As Integer

    FormatType2 As Integer

    FormatOptions1 As Integer

    FormatOptions2 As Integer

    DestinationDLLName As String * PE_DLL_NAME_LEN

    DestinationType1 As Integer

    DestinationType2 As Integer

    DestinationOptions1 As Integer

    DestinationOptions2 As Integer

    NFormatOptionsBytes As Integer

    NDestinationOptionsBytes As Integer

End Type
Delphi Record Listing
type

    PEDllNameType = array[0..PE_DLL_NAME_LEN-1] or Char;

    PEExportOptions = record

        StructSize: Word;

        formatDLLName: PEDllNameType;

        formatType: dWord;

        formatOptions: Pointer;

        destinationDLLName: PEDllNameType;

        destinationType: dWord;

        destinationOptions: Pointer;

        nFormatOptionsBytes: Word;

        nDestinationOptionsBytes: Word;

    end;


PEFieldMappingEventInfo

PEFieldMappingEventInfo contains information related to mapped database fields.

C Syntax
typedef struct PEFieldMappingEventInfo {

    WORD StructSize;

    PEReportFieldMappingInfo **reportFields;

    WORD nReportFields;

    PEReportFieldMappingInfo **databaseFields;

    WORD nDatabaseFields

} PEFieldMappingEventInfo;
Members

StructSize | Specifies the size of the PEFieldMappingEventInfo structure. Initialize the member to PE_SIZEOF_FIELDMAPPING_EVENT_INFO.
reportFields | A pointer to an array of pointers to PEReportFieldMappingInfo, containing information about fields in the report.
nReportFields | Size of the reportFields array (equivalent to the number of fields in the report).
databaseFields | A pointer to an array of pointers to PEReportFieldMappingInfo data members containing information about fields in the new database file.
nDatabaseFields | Size of the databaseField array.

Remarks

To map a report field to a database field the member mappingTo of each PEReportFieldMappingInfo , in the member reportFields array is assigned the index of the appropriate field in the member databaseFields array.

Delphi Record Listing
       type
              PEFieldMappingInfoPtr = ^PEReportFieldMappingInfo;

              PEFieldMappingInfoDoublePtr = ^PEFieldMappingInfoPtr;

        type

               PEFieldMappingEventInfo = record

                StructSize : Word;

                reportFields : PEFieldMappingInfoDoublePtr;

                nReportFields : Word;

                databaseFields : PEFieldMappingInfoDoublePtr;

                nDatabaseFields : Word;

         end;


PEFieldValueInfo

Specifies a field value in the fieldValueList of PEDrillOnDetailEventInfo.

C Syntax
typedef struct PEFieldValueInfo {

    WORD StructSize;

    WORD ignored;

    char fieldName [PE_FIELD_NAME_LEN];

    PEValueInfo fieldValue;

} PEFieldValueInfo;
Members

StructSize | Specifies the size of the PEFieldValueInfo structure. Initialize the member to PE_SIZEOF_FIELD_VALUE_INFO.
ignored | For 4 byte alignment. Ignore.
fieldName | Specifies the formula form of a field name (of length PE_FIELD_NAME_LEN = 512).
fieldValue | Specifies the field value for the selected Details area for the field specified by the field name.

Remarks

A selected Details area corresponds to a database record.

VB Type Listing
Type PEFieldValueInfo

    StructSize As Integer

    ignored As Integer

    fieldName As String

    fieldValue As PEValueInfo

End Type
Delphi Record Listing
type

    PEFieldNameType = array[0..PE_FIELD_NAME_LEN-1] of char;

    PEFieldValueInfo = record

        StructSize: Word;

        ignored: Word;

        fieldName: PEFieldNameType;

        fieldValue: PEValueInfo;

    end;


PEFontColorInfo

PEFontColorInfo contains information regarding chart title text fonts.

C Syntax
typedef struct PEFontColorInfo {

    WORD StructSize;

    char faceName[PE_FACE_NAME_LEN]; // empty string for no change

    short fontFamily;

    short fontPitch;

    short charSet;

    short pointSize;

    short isItalic;

    short isUnderlined;

    short isStruckOut;

    short weight;

    COLORREF color;

    short twipSize;

} PEFontColorInfo;
Members

StructSize | Specifies the size of the PEFontColorInfo structure. Initialize this member to PE_SIZEOF_FONT_COLOR_INFO.
faceName | Specifies the actual face name of the font [of length PE_FACE_NAME_LEN = 64]. The face name can typically come from a Font dialog box, be hard coded in the application or be chosen by the application from the fonts supported on the printer. For example, "Times New Roman". Pass an empty string ("") for no change.
fontFamily | Specifies the font family for the font. Use one of the following FF_XXX Font Family Constants.
 | Constant | Description
 | FF_DONTCARE | No change.
 | FF_ROMAN | Variable pitch font with serifs.
 | FF_SWISS | Fixed pitch font without serifs.
 | FF_MODERN | Fixed-pitch font, with or without serifs.
 | FF_SCRIPT | Handwriting-like font.
 | FF_DECORATIVE | Fancy display font.
fontPitch | Specifies the font pitch. Use a constant value for the font pitch as defined in WINDOWS.H. Use DEFAULT_PITCH for the current default setting.
charSet | Specifies the character set. Use a constant value for the character set as defined in WINDOWS.H. Use DEFAULT_CHARSET for the current default setting.
pointSize | Specifies the desired point size for the selected font. Use this member or member twipSize to specify the font size. If both members are non-zero, then this member will be ignored and twipSize will be used. Pass 0 for both twipSize and pointSize for no change.
isItalic | Specifies whether the font selected should be italicized. Use TRUE for Italic font, FALSE for non-Italic font, or PE_UNCHANGED for the current default setting.
isUnderlined | Specifies whether the font selected should be underlined. Use TRUE for Underline, FALSE for no Underline, or PE_UNCHANGED for the current default setting.
isStruckOut | Specifies whether the font selected should be struck out. Use TRUE for StruckOut, FALSE for no StruckOut, or PE_UNCHANGED for the current default setting.
weight | Specifies the weight of the font. Use a constant value from the weight values defined in WINDOWS.H. Use 0 for no change.
color | Specifies the RGB color value contained in COLORREF. Use PE_UNCHANGED_COLOR for the current default setting.
twipSize | Specifies the font size, in twips. Use this member or member pointSize to specify the font size. If both members are non-zero, then this member will be used and pointSize will be ignored. Pass 0 for both twipSize and pointSize for no change.

VB Type Listing
Type PEFontColorInfo

    StructSize As Integer

    faceName As String * PE_FACE_NAME_LEN

    fontFamily As Integer

    fontPitch As Integer

    charSet As Integer

    pointSize As Integer

    isItalic As Integer

    isUnderlined As Integer

    isStruckOut As Integer

    weight As Integer

    color As Long

    twipSize As Integer

End Type
Delphi Record Listing
type

  PEFaceNameType = array [0..PE_FACE_NAME_LEN-1] of Char;

  PEFontColorInfo = record

    StructSize   : Word;

    faceName     : PEFaceNameType;

    fontFamily   : Smallint;

    fontPitch    : Smallint;

    charSet      : Smallint;

    pointSize    : Smallint;

    isItalic     : Smallint;

    isUnderlined : Smallint;

    isStruckOut  : Smallint;

    weight       : Smallint;

    color        : COLORREF;

  end;


PEFormulaSyntax

PEFormulaSyntax is used by PEGetFormulaSyntax, and PESetFormulaSyntax, to retrieve and set the syntax for the current and following formula API calls.

C Syntax
#define PE_FS_SIZE 2
typedef struct PEFormulaSyntax {

    WORD StructSize;

    short formulaSyntax [PE_FS_SIZE];

} PEFormulaSyntax;
Members

StructSize | Specifies the size of the PEFormulaSyntax structure. Initialize this member to PE_SIZEOF_FORMULA_SYNTAX.
formulaSyntax | Specifies the formula syntax. Use one of the PE_FST_XXX Formula Syntax Constants, or PE_UNCHANGED for no change. Default value is PE_FST_CRYSTAL.

VB Syntax
Type PEFormulaSyntax

    StructSize As Integer

    formulaSyntax (0 To 1) As Integer

End Type


PEGeneralPrintWindowEventInfo

PEGeneralPrintWindowEventInfo contains general preview window event information. This structure is used for multiple events listed below. See Remarks.

C Syntax
typedef struct PEGeneralPrintWindowEventInfo {

    WORD StructSize;

    WORD ignored

    long windowHandle;

} PEGeneralPrintWindowEventInfo;
Members

StructSize | Specifies the size of the PEGeneralPrintWindowEventInfo structure. Initialize this member to PE_SIZEOF_GENERAL_PRINT_WINDOW_EVENT_INFO.
ignored | For 4 byte alignment. Ignore.
windowHandle | Frame window handle where the event happens.

Remarks

Structure PEGeneralPrintWindowEventInfo is used for the following events.

  • PE_CLOSE_PRINT_WINDOW_EVENT
  • PE_PRINT_BUTTON_CLICKED_EVENT
  • PE_EXPORT_BUTTON_CLICKED_EVENT
  • PE_FIRST_PAGE_BUTTON_CLICKED_EVENT
  • PE_PREVIOUS_PAGE_BUTTON_CLICKED_EVENT
  • PE_NEXT_PAGE_BUTTON_CLICKED_EVENT
  • PE_LAST_PAGE_BUTTON_CLICKED_EVENT
  • PE_CANCEL_BUTTON_CLICKED_EVENT
  • PE_PRINT_SETUP_BUTTON_CLICKED_EVENT
  • PE_REFRESH_BUTTON_CLICKED_EVENT
  • PE_ACTIVATE_PRINT_WINDOW_EVENT
  • PE_DEACTIVATE_PRINT_WINDOW_EVENT
VB Type Listing
Type PEGeneralPrintWindowEventInfo

    StructSize As Integer

    ignored As Integer

    windowHandle As Long

End Type
Delphi Record Listing
type

    PEGeneralPrintWindowEventInfo = record

        StructSize: Word;

        ignored: Word;

        windowHandle: HWnd;

    end;


PEGraphAxisInfo

PEGraphAxisInfo contains information about the gridline options, data ranges and formats and axis division features for the specified chart.

C Syntax
//axis division method
#define PE_ADM_AUTOMATIC                0
#define PE_ADM_MANUAL                   1
typedef struct PEGraphAxisInfo {

    WORD StructSize;

    short groupAxisGridLine;

    short dataAxisYGridLine;

    short dataAxisY2GridLine;

    short seriesAxisGridline;

    double dataAxisYMinValue;

    double dataAxisYMaxValue;

    double dataAxisY2MinValue;

    double dataAxisY2MaxValue;

    double seriesAxisMinValue;

    double seriesAxisMaxValue;

    short dataAxisYNumberFormat;

    short dataAxisY2NumberFormat;

    short seriesAxisNumberFormat;

    short dataAxisYAutoRange;

    short dataAxisY2AutoRange;

    short seriesAxisAutoRange;

    short dataAxisYAutomaticDivision;
//PE_ADM_* or PE_UNCHANGED for no change

    short dataAxisY2AutomaticDivision;
//PE_ADM_* or PE_UNCHANED for no change

    short seriesAxisAutomaticDivision;
//PE_ADM_* or PE_UNCHANED for no change

    long dataAxisYManualDivision;
//if dataAxisYAutomaticDivision is PE_ADM_AUTOMATIC, this field is
ignored

    long dataAxisY2ManualDivision;

    long seriesAxisManualDivision;
 //if seriesAxisAutomaticDivision is PE_ADM_AUTOMATIC, this field is
ignored

    short dataAxisYAutoScale;

    short dataAxisY2AutoScale;

    short seriesAxisAutoScale;

}  PEGraphAxisInfo;
Members

StructSize | Specifies the size of the PEGraphAxisInfo structure. Initialize this member to PE_SIZEOF_GRAPH_AXIS_INFO.
groupAxisGridLine | Specifies GridLine option. Use one of the PE_GGT_XXX Chart Gridline Constants, or PE_UNCHANGED for no change.
dataAxisYGridLine | Specifies GridLine option. Use one of the PE_GGT_XXX Chart Gridline Constants, or PE_UNCHANGED for no change.
dataAxisY2GridLine | Specifies GridLine option. Use one of the PE_GGT_XXX Chart Gridline Constants, or PE_UNCHANGED for no change.
seriesAxisGridline | Specifies GridLine option. Use one of the PE_GGT_XXX Chart Gridline Constants, or PE_UNCHANGED for no change.
dataAxisYMinValue | Specifies the minimum value for the axis.
dataAxisYMaxValue | Specifies the maximum value for the axis.
dataAxisY2MinValue | Specifies the minimum value for the axis.
dataAxisY2MaxValue | Specifies the maximum value for the axis.
seriesAxisMinValue | Specifies the minimum value for the axis.
seriesAxisMaxValue | Specifies the maximum value for the axis.
dataAxisYNumberFormat | Specifies the format for the display of numeric values on the chart. Use one of the PE_GNF_XXX Chart Number Format Constants, or PE_UNCHANGED for no change.
dataAxisY2NumberFormat | Specifies the format for the display of numeric values on the chart. Use one of the PE_GNF_XXX Chart Number Format Constants, or PE_UNCHANGED for no change.
seriesAxisNumberFormat | Specifies the format for the display of numeric values on the chart. Use one of the PE_GNF_XXX Chart Number Format Constants, or PE_UNCHANGED for no change.
dataAxisYAutoRange | Boolean, or PE_UNCHANGED for no change. If TRUE, the axis will autorange.
dataAxisY2AutoRange | Boolean, or PE_UNCHANGED for no change. If TRUE, the axis will autorange.
seriesAxisAutoRange | Boolean, or PE_UNCHANGED for no change. If TRUE, the axis will autorange.
dataAxisYAutomaticDivision | PE_ADM_AUTOMATIC, PE_ADM_MANUAL, or PE_UNCHANGED for no change.
dataAxisY2AutomaticDivision | PE_ADM_AUTOMATIC, PE_ADM_MANUAL, or PE_UNCHANGED for no change.
seriesAxisAutomaticDivision | PE_ADM_AUTOMATIC, PE_ADM_MANUAL, or PE_UNCHANGED for no change.
dataAxisYManualDivision | If the corresponding axis m_dataAxisYAutomaticDivision is PE_ADM_AUTOMATIC, this field is ignored.
dataAxisY2ManualDivision | If the corresponding axis m_dataAxisY2AutomaticDivision is PE_ADM_AUTOMATIC, this field is ignored.
seriesAxisManualDivision | If the corresponding axis m_seriesAxisAutomaticDivision is PE_ADM_AUTOMATIC, this field is ignored.
dataAxisYAutoScale | Boolean, or PE_UNCHANGED for no change. If TRUE, the axis will autoscale.
dataAxisY2AutoScale | Boolean, or PE_UNCHANGED for no change. If TRUE, the axis will autoscale.
seriesAxisAutoScale | Boolean, or PE_UNCHANGED for no change. If TRUE, the axis will autoscale.

VB Type Listing
Type PEGraphAxisInfo

    StructSize As Integer

    groupAxisGridLine As Integer

    dataAxisYGridLine As Integer

    dataAxisY2GridLine As Integer

    seriesAxisGridline As Integer

    dataAxisYMinValue As Double

    dataAxisYMaxValue As Double

    dataAxisY2MinValue As Double

    dataAxisY2MaxValue As Double

    seriesAxisMinValue As Double

    seriesAxisMaxValue As Double

    dataAxisYNumberFormat As Integer

    dataAxisY2NumberFormat As Integer

    seriesAxisNumberFormat As Integer

    dataAxisYAutoRange As Integer

    dataAxisY2AutoRange As Integer

    seriesAxisAutoRange As Integer

    dataAxisYAutomaticDivision As Integer

    dataAxisY2AutomaticDivision As Integer

    seriesAxisAutomaticDivision As Integer

    dataAxisYManualDivision As Long

    dataAxisY2ManualDivision As Long

    seriesAxisManualDivision As Long

    dataAxisYAutoScale As Integer

    dataAxisY2AutoScale As Integer

    seriesAxisAutoScale As Integer

End Type
Delphi Record Listing
type

  PEGraphAxisInfo = record

    StructSize         : Word;

    groupAxisGridLine  : Smallint;

    dataAxisYGridLine  : Smallint;

    dataAxisY2GridLine : Smallint;

    seriesAxisGridline : Smallint;

    dataAxisYMinValue  : double;

    dataAxisYMaxValue  : double;

    dataAxisY2MinValue : double;

    dataAxisY2MaxValue : double;

    seriesAxisMinValue : double;

    seriesAxisMaxValue : double;

    dataAxisYNumberFormat  : Smallint;

    dataAxisY2NumberFormat : Smallint;

    seriesAxisNumberFormat : Smallint;

    dataAxisYAutoRange  : Smallint;

    dataAxisY2AutoRange : Smallint;

    seriesAxisAutoRange : Smallint;

    dataAxisYAutomaticDivision  : Smallint;

    dataAxisY2AutomaticDivision : Smallint;

    seriesAxisAutomaticDivision : Smallint;

    dataAxisYManualDivision  : Longint;

    dataAxisY2ManualDivision : Longint;

    seriesAxisManualDivision : LongInt;

  end;


PEGraphOptionInfo

PEGraphOptionInfo contains information about chart appearance and is used by PEGetGraphOptionInfo, and PESetGraphOptionInfo.

C Syntax
typedef struct PEGraphOptionInfo {

    WORD StructSize;

    short graphColour;

    short showLegend;

    short legendPosition;

    short pieSize;

    short detachedPieSlice;

    short barSize;

    short verticalBars;

    short markerSize;

    short markerShape;

    short dataPoints;

    short dataValueNumberFormat;

    short viewingAngle;

    short legendLayout;

} PEGraphOptionInfo;
Members

StructSize | Specifies the size of the PEGraphOptionsInfo structure. Initialize this member to PE_SIZEOF_GRAPH_OPTION_INFO.
graphColour | Use one of the PE_GCR_XXX Chart Options Constants, or PE_UNCHANGED for no change.
showLegend | BOOLEAN. Use TRUE to show the chart legend, FALSE to hide the chart legend, or PE_UNCHANGED for no change.
legendPosition | Use one of the PE_GLP_XXX Chart Options Constants, or PE_UNCHANGED for no change. Valid only if showLegend is TRUE.
pieSize | For pie charts and doughnut charts, use one of the PE_GPS_XXX Chart Pie Size Constants, or PE_UNCHANGED for no change.
detachedPie Slice | For pie charts and doughnut charts, use one of the PE_GDPS_XXX Chart Slice Detachment Constants, or PE_UNCHANGED for no change.
barSize | For bar charts, use one of the PE_GBS_XXX Chart Bar Size Constants, or PE_UNCHANGED for no change.
verticalBars | BOOLEAN. For bar charts, use TRUE if the chart will have vertical bars, FALSE if the chart will not have vertical bars, or PE_UNCHANGED for no change.
markerSize | For line charts and bar charts, use one of the PE_GMS_XXX Chart Marker Size Constants, or PE_UNCHANGED for no change.
markerShape | For line charts and bar charts, use one of the PE_GMSP_XXX Chart Marker Shape Constants, or PE_UNCHANGED for no change.
dataPoints | Use one of the PE_GDP_XXX Chart Data Point Constants, or PE_UNCHANGED for no change.
dataValue NumberFormat | Use one of the PE_GNF_XXX Chart Number Format Constants, or PE_UNCHANGED for no change.
viewingAngle | For 3D charts, use one of the PE_GVA_XXX Chart Viewing Angle Constants, or PE_UNCHANGED for no change.
legendLayout | Specifies the legend layout. Use one of the PE_GLL_XXX Chart Legend Layout Constants.

VB Type Listing
Type PEGraphOptionInfo

    StructSize As Integer

    graphColour As Integer

    showLegend As Integer

    legendPosition As Integer

    pieSize As Integer

    detachedPieSlice As Integer

    barSize As Integer

    verticalBars As Integer

    markerSize As Integer

    markerShape As Integer

    dataPoints  As Integer

    dataValueNumberFormat As Integer

    viewingAngle As Integer

    legendLayout As Integer

End Type
Delphi Record Listing
type

  PEGraphOptionInfo = record

    StructSize       : Word;

    graphColour      : Smallint;

    showLegend       : Smallint;

    legendPosition   : Smallint;

    pieSize          : Smallint;

    detachedPieSlice : Smallint;

    barSize          : Smallint;

    verticalBars     : Smallint;

    markerSize       : Smallint;

    markerShape      : Smallint;

    dataPoints       : Smallint;

    dataValueNumberFormat : Smallint;

    viewingAngle     : Smallint;

  end


PEGraphTypeInfo

PEGraphTypeInfo contains information about the type of the specified chart and is used by PEGetGraphTypeInfo and PESetGraphTypeInfo.

C Syntax
typedef struct PEGraphTypeInfo {

    WORD StructSize;

    short graphType;

    short graphSubtype;

} PEGraphTypeInfo;
Members

StructSize | Specifies the size of the PEGraphTypeInfo structure. Initialize this member to PE_SIZEOF_GRAPH_TYPE_INFO.
graphType | Uses one of the PE_GT_XXX Graph Type Constants, or PE_UNCHANGED for no change.
graphSubtype | Uses one of the PE_GST_XXX Graph Subtype Constants, or PE_UNCHANGED for no change.

VB Type Listing
Type PEGraphTypeInfo

    StructSize As Integer

    graphType As Integer

    graphSubtype As Integer

End Type
Delphi Record Listing
type

  PEGraphTypeInfo = record

    StructSize   : Word;

    graphType    : Smallint;

    graphSubtype : Smallint;

  end;


PEGroupOptions

PEGroupOptions contains information about report group options. This information is used by PEGetGroupOptions to retrieve current options and by PESetGroupOptions to pass new options.

C Syntax
typedef struct PEGroupOptions {

    WORD StructSize;

    short condition;

    char  fieldName [PE_FIELD_NAME_LEN];

    short sortDirection;

    short repeatGroupHeader;

    short keepGroupTogether;

    short topOrBottomNGroups;

    char  topOrBottomNSortFieldName [PE_FIELD_NAME_LEN];

    short nTopOrBottomGroups;

    short discardOtherGroups;

    short hierarchicalSorting;

    char  instanceIDField [PE_FIELD_NAME_LEN];

    char  parentIDField [PE_FIELD_NAME_LEN];

    long  groupIndent;

} PEGroupOptions;
Members

StructSize | Specifies the size of the PEGroupOptions structure. Initialize to PE_SIZEOF_GROUP_OPTIONS.
condition | Specifies the condition setting for the selected group section. When getting, use PE_GC_TYPEMASK and PE_GC_CONDITIONMASK to decode the condition. When setting, pass a PE_GC_XXX Group Condition Constants, or PE_UNCHANGED for no change.
fieldName | Specifies the field name of the group field (of length PE_FIELD_NAME_LEN = 512). Use formula form or leave empty for no change.
sortDirection | Specifies one of the Sort Order Constants or PE_UNCHANGED for no change.
repeatGroupHeader | TRUE, FALSE, or PE_UNCHANGED for no change.
keepGoupTogether | TRUE, FALSE, or PE_UNCHANGED for no change.
topOrBottomNGroups | Use one of the following PE_GO_TBN_XXX constants or PE_UNCHANGED for no change.
 | Constant | Description
 | PE_GO_TBN_ALL_GROUPS_ UNSORTED | There is no group sorting or Top/Bottom N for this level of grouping.
 | PE_GO_TBN_ALL_GROUPS_ SORTED | There is group sorting, but not Top/Bottom N.
 | PE_GO_TBN_TOP_N_GROUPS | Top N groups will be selected.
 | PE_GO_TBN_BOTTOM_N_GROUPS | Bottom N groups will be selected.
topOrBottomNSort FieldName | Specifies the field name (of length PE_FIELD_NAME_LEN = 512) of the summary field by which the groups are ordered. Use formula form or leave empty for no change.
nTopOrBottomGroups | Specifies the number of groups to keep. Use 0 to keep all groups and PE_UNCHANGED for no change.
discardOtherGroups | Determines whether the remaining groups are collected into an Others group or discarded. TRUE, FALSE, or PE_UNCHANGED for no change.
hierarchicalSorting | Specifies whether or not sorting is hierarchical. TRUE, FALSE, or PE_UNCHANGED for no change.
instanceIDField | Specifies the instance ID field (of length PE_FIELD_NAME_LEN = 512) for hierarchical sorting
parentIDField | Specifies the parent ID field (of length PE_FIELD_NAME_LEN = 512) for hierarchical sorting
groupIndent | Specifies the indent for hierarchical group sorting, in twips.

Remarks

If topOrBottomNGroups is PE_GO_TBN_TOP_N_GROUPS or PE_GO_TBN_BOTTOM_N_GROUPS, all the group sort fields related to this group will be deleted. A new group sort field will be added with the sort direction of descending or ascending. The group sort field will be sorted by specifying topOrBottomNSortFieldName if it is not empty. It will be sorted by the first group sort field name related to this group (before it is deleted) if topOrBottomNSortFieldName is empty.

VB Type Listing
Type PEGroupOptions

    StructSize As Integer

    condition As Integer

    fieldName As String * PE_FIELD_NAME_LEN

    sortDirection As Integer

    repeatGroupHeader As Integer

    keepGroupTogether As Integer

    topOrBottomNGroups As Integer * PE_FIELD_NAME_LEN

    topOrBottomNSortFieldName As String * PE_FIELD_NAME_LEN

    nTopOrBottomGroups As Integer

    discardOtherGroups As Integer

    hierarchicalSorting As Integer

    instanceIDField As String * PE_FIELD_NAME_LEN

    parentIDField As String * PE_FIELD_NAME_LEN

    groupIndent As Long

End Type
Delphi Record Listing
type

    PEFieldNameType = array[0..PE_FIELD_NAME_LEN-1] of char;

    PEGroupOptions = record

        StructSize: Word;

        condition: smallint;

        fieldName: PEFieldNameType;

        sortDirection: smallint;

        repeatGroupHeader: smallint;

        keepgroupTogether: smallint;

        topOrBottomNGroups: smallint;

        topOrBottomNSortFieldName: PEFieldNameType;

        nTopOrBottomGroups: smallint;

        discardOtherGroups: smallint

    end;


PEGroupTreeButtonClickedEventInfo

Provides information about the group tree button clicked event, when the callback function is called with the event ID equal to PE_GROUP_TREE_BUTTON_CLICKED_EVENT.

C Syntax
typedef struct PEGroupTreeButtonClickedEventInfo {

    WORD StructSize;

    short visible;

    long windowHandle;

} PEGroupTreeButtonClickedEventInfo;
Members

StructSize | Specifies the size of the PEGroupTreeButtonClickedEventInfo structure. Initialize this member to PE_SIZEOF_GROUP_TREE_BUTTON_CLICKED_EVENT_INFO.
visible | Indicates whether the group tree is shown or hidden.
window Handle | Frame window handle where the event happens.

VB Type Listing
Type PEGroupTreeButtonClickedEventInfo

    StructSize As Integer

    visible As Integer

    windowHandle As Long

End Type
Delphi Record Listing
type

    PEGroupTreeButtonClickedEventInfo = record

        StructSize: Word;

        visible: smallint;

        windowHandle: HWnd;

    end;


PEHyperlinkEventInfo

PEHyperlinkEventInfo contains information related to the specified hyperlink.

C Syntax
typedef struct PEHyperlinkEventInfo {

    WORD StructSize;

    WORD ignored;

    long windowHandle;

    char FAR *hyperlinkText;

} PEHyperlinkEventInfo;
Members

StructSize | Specifies the size of the PEHyperlinkEventInfo structure. Initialize this member to PE_SIZEOF_HYPERLINKEVENTINFO.
ignored | For 4-byte alignment. Ignored.
windowHandle | Specifies HWND for the window in which the event occurred.
hyperlinkText | Specifies a pointer to the hyperlink text associated with the specified object. The memory referenced by the pointer is freed after calling the callback function.


PEJobInfo

Contains print job process and display information that is used by PEGetJobStatus.

C Syntax
typedef struct PEJobInfo {

    WORD StructSize;

    DWORD NumRecordsRead;

    DWORD NumRecordsSelected;

    DWORD NumRecordsPrinted;

    WORD DisplayPageN;

    WORD LatestPageN;

    WORD StartPageN;

    BOOL printEnded;

} PEJobInfo;
Members

StructSize | Specifies the size of the PEJobInfo structure. Initialize to PE_SIZEOF_JOB_INFO.
NumRecordsRead | Specifies the number of records actually processed.
NumRecordsSelected | Specifies the number of records selected for inclusion in the report out of the total number of records read.
NumRecordsPrinted | Specifies the number of records actually printed or previewed.
DisplayPageN | Specifies the page number of the currently displayed page in the preview window.
LatestPageN | Specifies the page being generated. Once the printing is complete, this value is the number of the last page.
StartPageN | Specifies the number of the starting page. The value will normally be 1, but you can specify something else using PESetPrintOptions.
printEnded | Specifies whether or not the printing process is completed. TRUE indicates that this process is completed; FALSE indicates that is not yet complete. When printing to a preview window, printEnded is True only when the last page is reached.

VB Type Listing
Type PEJobInfo

    StructSize As Integer

    NumRecordsRead As Long

    NumRecordsSelected As Long

    NumRecordsPrinted As Long

    DisplayPageN As Integer

    LatestPageN As Integer

    StartPageN As Integer

    PrintEnded As Long

Type PEJobInfo
Delphi Record Listing
type

    PEJobInfo = record

        StructSize: Word;

        NumRecordsSelected: longint;

        NumRecordsPrinted: longint;

        DisplayPageN: Word;

        LatestPageN: Word;

        StartPageN: Word;

        PrintEnded: Bool;

    end;


PELaunchSeagateAnalysisEventInfo

PELaunchSeagateAnalysisEventInfo contains information related to the launching of Seagate Analysis.

Note: Seagate Analysis is now known as Crystal Analysis.

C Syntax
typedef struct PELaunchSeagateAnalysisEventInfo {

    WORD StructSize;

    WORD ignored;

    long windowHandle;

    char FAR *pathFile;

} PELaunchSeagateAnalysisEventInfo;
Members

StructSize | Specifies the size of the PELaunchSeagateAnalysisEventInfo structure. Initialize this member to PE_SIZEOF_LAUNCH_SEAGATE_ANALYSIS_EVENT_INFO.
ignored | For 4-byte alignment. Ignored.
window Handle | Specifies HWND for the window in which the event occurred.
pathFile | Specifies a pointer to the path and filename of the temporary report. The memory referenced by the pointer is freed after calling the callback function.


PELogOnInfo

PELogOnInfo contains log on information that is used by PEGetNthTableLogOnInfo; PESetNthTableLogOnInfo; PELogOnServer; and PELogOffServer for logging on and off SQL and password-protected non-SQL databases.

C Syntax
typedef struct PELogOnInfo {

    WORD StructSize;

    char ServerName [PE_SERVERNAME_LEN];

    char DatabaseName [PE_DATABASENAME_LEN];

    char UserID [PE_USERID_LEN];

    char Password [PE_PASSWORD_LEN];

} PELogOnInfo;
Members

StructSize | Specifies the size of the PELogOnInfo structure. Initialize this member to PE_SIZEOF_LOGON_INFO.
ServerName | Specifies the logon name for the server (of length PE_SERVERNAME_LEN = 128, NULL-terminated) used to create the report. See Remarks below.
DatabaseName | Specifies the database logon name (of length PE_DATABASENAME_LEN = 128, NULL-terminated) for the database used to create the report. See Remarks below.
UserID | Specifies the user I.D (of length PE_USERID_LEN = 128, NULL-terminated) necessary to log on to the server. See Remarks below.
Password | Specifies the password (of length PE_PASSWORD_LEN = 128, NULL-terminated) necessary to log on to the server. See Remarks below.

Remarks
  • All strings must be null-terminated.
  • Password is undefined when getting information from the report.
  • Password must be set using PEGetNthTableLogOnInfo. You can pass an empty string ("") for ServerName, DatabaseName, or UserID, and the program will use the value that's already set in the report. If you want to override a value that's already set in the report, use a non-empty string (for example, "Server A") for the other parameters as well.
  • For Netware SQL, pass the dictionary path name in member ServerName and data path name in member DatabaseName.
  • If your report uses a Microsoft Access database via ODBC, the data source indicated in the ServerName parameter must specify an Access database file. An ODBC data source based on the Access driver with no database specified cannot be used at runtime.
  • For Essbase databases, pass the Essbase application and database to the DatabaseName member with a comma between each. For example:

    Sample,Basic

VB Type Listing
Type PELogOnInfo

    StructSize As Integer

    ServerName As String * PE_SERVERNAME_LEN

    DatabaseName As String * PE_DATABASENAME_LEN

    UserID As String * PE_USERID_LEN

    Password As String * PE_PASSWORD_LEN

End Type
Delphi Record Listing
type

    PELogonServerType = array[0..PE_SERVERNAME_LEN-1] of char;

    PELogonDBType = array[0..PE_DATABASENAME_LEN-1] of char;

    PELogonUserType = array[0..PE_USERID_LEN-1] of char;

    PELogonPassType = array[0..PE_PASSWORD_LEN-1] of char;

    PELogOnInfo = record

        StructSize: Word;

        ServerName: PELogonServerType;

        DatabaseName: PELogonDbType;

        UserId: PELogonUserType;

        Password: PELogonPassType;

    end;


PEMouseClickEventInfo

PEMouseClickEventInfo contains information associated with a mouse click event when the callback function is called with event ID equal to PE_RIGHT/MIDDLE/LEFT_CLICK_EVENT.

C Syntax
typedef struct PEMouseClickEventInfo {

    WORD StructSize;

    long windowHandle;

    UINT clickAction;

    UINT clickFlags;

    int xOffset;

    int yOffset;

    PEValueInfo fieldValue;

    DWORD objectHandle;

    short sectionCode

} PEMouseClickedEventInfo;
Members

StructSize | Specifies the size of the PEMouseClickEventInfo structure. Initialize this member to PE_SIZEOF_MOUSE_CLICK_EVENT_INFO.
windowHandle | Specifies the handle of the frame window in which the mouse click event occurred.
clickAction | Indicates the click action. Uses one of the following PE_MOUSE_XXX constants.
 | Constant | Description
 | PE_MOUSE_NOTSUPPORTED |  |
 | PE_MOUSE_DOWN |  |
 | PE_MOUSE_UP |  |
 | PE_MOUSE_DOUBLE_CLICK | For Mouse Left click or Mouse Middle click.
clickFlags | Indicates the source of the event, which can be any combination of the following PE_CF_XXX virtual key state-mask constants.
 | Constant | Value | Description
 | PE_CF_NONE | 0x0000 | No button pressed
 | PE_CF_LBUTTON | 0x0001 | Left mouse button
 | PE_CF_RBUTTON | 0x0002 | Right mouse button
 | PE_CF_SHIFTKEY | 0x0004 | Shift key
 | PE_CF_CONTROLKEY | 0x0008 | Control key
 | PE_CF_MBUTTON | 0x00010 | Center mouse button
xOffset | X-coordinate of cursor during mouse click in pixels.
yOffset | Y-coordinate of cursor during mouse click in pixels.
fieldValue | The PEValueInfo, structure containing information about the value of the object at the click point, if it is a field object (excluding MEMO and BLOB fields), else valueType element = PE_VI_NOVALUE.
objectHandle | Specifies the handle of the design view object.
sectionCode | Specifies the Section Codes for the section in which the click occurred. See Working with section codes.

Delphi Record Listing
type

   PEMouseClickEventInfo = record

    StructSize : Word;

    windowHandle : LongInt;

    clickAction : integer;

    clickFlags : integer;    {

    xOffset : integer;

    yOffset : integer;

    fieldValue : PEValueInfo;

    objectHandle : DWord;

    sectionCode : smallint;

end;


PEObjectInfo

PEObjectInfo contains information related to the type, location, and appearance of an object.

C Syntax
typedef struct PEObjectInfo {

    WORD StructSize;

    WORD objectType;

    long xOffset;

    long yOffset;

    long width;

    long height;

    short sectionCode;

} PEObjectInfo;
Members

StructSize | Specifies the size of the PEObjectInfo structure. Initialize this member to PE_SIZEOF_OBJECT_INFO.
objectType | Specifies the object type. Use one of the PE_OI_XXX Object Type Constants.
xOffset | Specifies the X-offset of the object in the section, in twips, or PE_UNCHANGED for no change.
yOffset | Specifies the Y-offset of the object in the section, in twips, or PE_UNCHANGED for no change.
width | Specifies the width of the object, in twips, or PE_UNCHANGED for no change.
height | Specifies the height of the object, in twips, or PE_UNCHANGED for no change.
sectionCode | Specify the section code for the section containing the object, or PE_UNCHANGED for no change from the current section.


PEParameterFieldInfo

The PEParameterFieldInfo structure contains information related to parameter fields in a report. This structure is used by PEGetNthParameterField to get information about a specific parameter field and by PESetNthParameterField to change a specific parameter field.

C Syntax
typedef struct PEParameterFieldInfo {

    WORD StructSize;

    WORD ValueType;

    WORD DefaultValueSet;

    WORD CurrentValueSet;

    char Name [PE_PF_NAME_LEN];

    char Prompt [PE_PF_PROMPT_LEN];

    char DefaultValue [PE_PF_VALUE_LEN];

    char CurrentValue [PE_PF_VALUE_LEN];

    char ReportName [PE_PF_REPORT_NAME_LEN];

    WORD needsCurrentValue;

    WORD isLimited;

    double MinSize;

    double MaxSize;

    char EditMask [PE_PF_EDITMASK_LEN];

    WORD isHidden;

} PEParameterFieldInfo;
Members

If you wish to set a parameter to NULL, set the CurrentValue to CRWNULL. CRWULL is of Type String and is independent of the data type of the parameter.

StructSize | Specifies the size of the PEParameterFieldInfo structure. Initialize this member to PE_SIZEOF_PARAMETER_FIELD_INFO.
ValueType | Specifies the data type of the parameter field. The Crystal Report Engine supports the data types and associated PE_PF_XXX Parameter Field Value Type Constants.
DefaultValueSet | For backward compatibility for existing applications only. For all new development set this member to FALSE and use PEAdd/GetNth/SetNthParameterDefaultValue. See Remarks below. This member indicates whether a value is assigned to the DefaultValue parameter field. Use TRUE to indicate that a new value is set or FALSE to indicate no change.
CurrentValueSet | For backward compatibility for existing applications only. For all new development set this member to FALSE and use PEAdd/GetNth/SetNthParameterCurrentValue. See Remarks below. This member indicates whether a value is assigned to the CurrentValue parameter field. Use TRUE to indicate that a new value is set or FALSE to indicate no change.
Name | Specifies the name of the parameter field (of length PE_PF_NAME_LEN = 256, NULL-terminated) to be assigned a new value.
Prompt | Specifies the prompting text (of length PE_PF_PROMPT_LEN = 256, NULL-terminated), if any, that will appear when the user runs the report for the first time or refreshes the data.
DefaultValue | For existing applications only; not for new development. See Remarks below. Specifies the default value assigned to the parameter field. If the DefaultValueSet member is FALSE, this value is meaningless. DefaultValue can be a Number, Currency, Date, DateTime, Time, Boolean, or String (of length PE_PF_VALUE_LEN = 256).
CurrentValue | For existing applications only; not for new development. See Remarks below. Specifies the current value assigned to the parameter field. If CurrentValueSet is FALSE, this value is meaningless. CurrentValue can be a Number, Currency, Date, DateTime, Time, Boolean, or String (of length PE_PF_VALUE_LEN = 256).
ReportName | The name of the report (of length PE_PF_REPORT_NAME_LEN = 128) where the field belongs (used only with PEGetNthParameterField).
needsCurrentValue | Returns FALSE if the parameter is linked, not in use, or has current value set.
isLimited | For string values, this will be TRUE if the string is limited on length. For other types, it will be TRUE if the parameter is limited by a range. This capability is not supported currently in Web Viewers.
MinSize | Use for numeric and string fields. Depending on the value type, contains the minimum length of the string or minimum numeric value. For non-numeric and non-string fields (for example, Date/Time), use PEGetParameterMinMaxValue, and PESetParameterMinMaxValue. This capability is not supported currently in Web Viewers.
MaxSize | Use for numeric and string fields. Depending on the value type, contains the maximum length of the string or maximum numeric value. For non-numeric and non-string fields (for example, Date/Time), use PEGetParameterMinMaxValue, and PESetParameterMinMaxValue. This capability is not supported currently in Web Viewers.
EditMask | An edit mask (of length PEP_PF_EDITMASK_LEN = 256) that restricts what may be entered for string parameters. This capability is not supported currently in Web Viewers.
isHidden | TRUE if an essbase sub var. This capability is not supported currently in Web Viewers.

Remarks
  • Regarding members DefaultValueSet, CurrentValueSet, DefaultValue, and CurrentValue:
      • To support backward compatibility for existing applications, when Default/CurrentValueSet is set to TRUE, the values in Default/CurrentValue will override any values set by PEAdd/Get/SetParameterDefault/CurrentValue.
      • PEParameterFieldInfo does not process Max or Min parameters if they are passed in after a Date, Time or Date/Time parameter.
      • For new application development, the Default/CurrentValueSet must be set to FALSE, so that the Default/CurrentValue members of PEParameterFieldInfo will be ignored and the values associated with PEAdd/Get/SetNthParameterDefault/CurrentValue will be valid. Developers should use the following calls in new applications to access default and current value lists.

        PEAddParameterCurrentRange

        PEAddParameterCurrentValue

        PEAddParameterDefaultValue

        PEGetNParameterCurrentRanges

        PEGetNParameterCurrentValues

        PEGetNParameterDefaultValues

        PEGetNthParameterCurrentRange

        PEGetNthParameterCurrentValue

        PEGetNthParameterDefaultValue

        PESetNthParameterDefaultValue

  • To determine if a parameter field is a stored procedure, use PEGetNthParameterType, or PEGetNthParameterField.
VB type listing
Type PEParameterFieldInfo

    StructSize As Integer

    ValueType As Integer

    DefaultValueSet As Integer

    CurrentValueSet As Integer

    Name As String * PE_PF_NAME_LEN

    Prompt As String * PE_PF_PROMPT_LEN

    DefaultValue As String * PE_PF_VALUE_LEN

    CurrentValue As String * PE_PF_VALUE_LEN

    ReportName As String * PE_PF_REPORT_NAME_LEN

    needsCurrentValue As Integer

    isLimited As Integer

    MinSize As Double

    MaxSize As Double

    EditMask As String * PE_PF_EDITMASK_LEN

    isHidden As Integer

End Type
Delphi listing
type

    PEParameterFieldValueType = array[0..PE_PF_NAME_LEN-1] of char;

    PE_PF_ReportNameType = array[0..PE_PF_REPORT_NAME_LEN-1] of char;

    PEParameterFieldNameType  = array [0..PE_PF_NAME_LEN-1] of Char;

    PEParameterFieldEditMaskType = array [0..PE_PF_EDITMASK_LEN-1] of

                                Char;

    PEParameterFieldInfo = record

        structSize: Word;

        ValueType: Word;

        DefaultValueSet: Word;

        CurrentValueSet: Word;

        Name: PEParameterFieldNameType;

        Prompt: PEParameterFieldTextType;

        DefaultValue: PEParameterFieldValueType;

        CurrentValue: PEParameterFieldValueType;

        ReportName: PE_PF_ReportNameType;

        needsCurrentvalue: Word;

        isLimited: Word;

        MinSize: double;

        MaxSize: double;

        EditMask: PEParameterFieldEditMaskType;

        isHidden: Word;

    end;


PEParameterPickListOption

PEParameterPickListOption contains information related to parameter sort methods.

C Syntax
typedef struct PEParameterPickListOption {

        WORD  StructSize;

        short showDescOnly;

        short sortMethod;

        short sortBasedOnDesc;

} PEParameterPickListOption;
Members

StructSize | Specifies the size of the PEParameterFieldInfo structure. Initialize this member to PE_SIZEOF_PICK_LIST_OPTION.
showDescOnly | Boolean, or PE_UNCHANGED for no change.
sortMethod | Use one of thePE_OR_XXX Sort Method Constants, or PE_UNCHANGED for no change.
sortBasedOnDesc | Boolean, or PE_UNCHANGED for no change.

VB Type Listing
Type PEParameterPickListOption

    StructSize As Integer

    showDescOnly As Integer

    sortMethod As Integer

    sortBasedOnDesc As Integer

End Type
Delphi Record Listing
type

  PEParameterPickListOption = record

    StructSize      : Word;

    showDescOnly    : Smallint;

    sortMethod      : Smallint;

    sortBasedOnDesc : Smallint;

  end;


PEParameterValueInfo

PEParameterValueInfo contains information about the type of value(s) that a specified parameter field can hold. See Working with section codes.

C Syntax
typedef struct PEParameterValueInfo {

    WORD StructSize;

    short isNullable;

    short disallowEditing;

    short allowMultipleValues;

    short hasDiscreteValues;

    short partOfGroup;

    short groupNum;

    short mutuallyExclusiveGroup

} PEParameterValueInfo;
Members

StructSize | Specifies the size of the PEParameterValueInfo structure. Set this member to PE_SIZEOF_PARAMETER_VALUE_INFO
isNullable | Specifies whether or not the parameter field can be set to NULL. Set to TRUE, FALSE or PE_UNCHANGED if no change.
disallowEditing | Indicates whether the parameter field value can be edited. Set to TRUE, FALSE, or PE_UNCHANGED if no change.
allowMultipleValues | Specifies whether or not the parameter field can contain multiple values. Set to TRUE, FALSE or PE_UNCHANGED if no change.
hasDiscreteValues | Specifies whether or not the parameter field contains discreet values, range values, or both. Uses one of the following PE_DR_XXX Constants. See Working with Parameter Values and Ranges.
 | Constant | Description
 | PE_DR_HASRANGE | Only ranges are present.
 | PE_DR_HASDISCRETE | Only discrete values are present.
 | PE_DR_HASDISCRETEANDRANGE | Both discrete values and ranges are present.
partOfGroup | Specifies whether or not the parameter field is a member of a group. Set to TRUE, FALSE or PE_UNCHANGED if no change.
groupNum | Specifies the group number or set to PE_UNCHANGED if no change.
mutuallyExclusive Group | Specifies whether or not the parameter field is a member of a mutually exclusive group. Set to TRUE, FALSE or PE_UNCHANGED if no change.

VB Type Listing
Type PEParameterValueInfo

     StructSize As Integer

     isNullable As Integer

     disallowEditing As Integer

     allowMultipleValues As Integer

     hasDiscreteValues As Integer

     partOfGroup As Integer

     groupNum As Integer

     mutuallyExclusiveGroup As Integer

  End Type
Delphi Record Listing
type

    PEParameterValueInfo = record

    StructSize : Word;

   isNullable : smallint;

   disallowEditing : smallint;

   allowMultipleValues : smallint;

   hasDiscreteValues : smallint;

   partOfGroup : smallint;    {

   groupNum : smallint;

   mutuallyExclusiveGroup : smallint;

end;


PEPrintOptions

PEPrintOptions contains printing specifications that are used by the PEGetPrintOptions, to retrieve current options and PESetPrintOptions,to pass new options. These specifications are the same as those that can be set using the Print common dialog box.

C Syntax
typedef struct PEPrintOptions {

    WORD StructSize;

    unsigned short startPageN;

    unsigned short stopPageN;

    unsigned short nReportCopies;

    unsigned short collation;

    char outputFileName [PE_FILE_PATH_LEN];

} PEPrintOptions;
Members

StructSize | Specifies the size of the PEPrintOptions structure. Initialize this member to PE_SIZEOF_PRINT_OPTIONS.
startPageN | Specifies the first page that you want to print. Page numbers are 1-based (Page 1 = 1, Page 2 = 2, etc.). Use 0 if you want to retain the existing settings.
stopPageN | Specifies the last page that you want to print. Page numbers are 1-based (Page 1 = 1, Page 2 = 2, etc.). Use 0 if you want to retain the existing settings.
nReportCopies | Specifies the number of copies that you want to print. Copy numbers, like page numbers, are 1-based. Use 0 if you want to retain the existing settings.
collation | Indicates whether or not you want the program to collate the copies (if you are printing multiple copies of a multiple page report). For this parameter, use one of the following constants:
 | Constant | Description
 | PE_UNCOLLATED | Prints multiple copies of a multiple page report uncollated (Page order = 1, 1, 1, 2, 2, 2, 3, 3, 3, etc.).
 | PE_COLLATED | Prints multiple copies of a multiple page report collated (Page order = 1, 2, 3,..., 1, 2, 3,..., etc.).
 | PE_DEFAULTCOLLATION | Prints multiple copies of a multiple page report using the collation settings as specified in the report.
outputFileName | Specifies a path and file name (of length PE_FILE_PATH_LEN = 512) if the report is printed to a file.

VB Type Listing
Type PEPrintOptions

    StructSize As Integer

    StartPageN As Integer

    StopPageN As Integer

    nReportCopies As Integer

    collation As Integer

    outputFileName As String * PE_FILE_PATH_LEN

End Type
Delphi Record Listing
type

  PEOutputFileNameType = array [0..PE_FILE_PATH_LEN-1] of Char;

  PEPrintOptions  = record

        StructSize: Word;

        StartPageN: Word;

        StopPageN: Word;

        nReportCopies: Word;

        Collation: Word;

        outputFileName: PEOutputFileNameType ;

    end;


PEReadingRecordsEventInfo

PEReadingRecordsEventInfo contains information about records read when a callback function is called with event ID equal to PE_READING_RECORDS_EVENT.

C Syntax
typedef struct PEReadingRecordsEventInfo {

    WORD StructSize;

    short cancelled;

    long recordsRead;

    long recordsSelected;

    short done;

} PEReadingRecordsEventInfo;
Members

StructSize | Specifies the size of the PEReadingRecordsEventInfo structure. Initialize this member to PE_SIZEOF_READING_RECORDS_EVENT_INFO.
cancelled | Boolean value indicates whether the reading records is canceled.
recordsRead | Indicates how many records have been read.
recordsSelected | Indicates how many records have been selected.
done | Boolean value indicates whether reading records is finished.

VB Type Listing
Type PEReadingRecordsEventInfo

    StructSize As Integer

    cancelled As Integer

    recordsRead As Long

    recordsSelected As Long

    done As Integer

End Type
Delphi Record Listing
type

    PEReadingRecordsEventInfo = record

        StructSize: Word;

        cancelled: smallint;

        recordsRead: longint;

        recordsSelected: longint;

        done: smallint;

end;


PEReportFieldMappingInfo

PEReportFieldMappingInfo contains information required to associate (map) a report field to a database field that has been changed.

C Syntax
typedef struct PEReportFieldMappingInfo {

    WORD StructSize;

    WORD valueType;

    char tableAliasName[PE_TABLE_NAME_LEN];

    char databaseFieldName[PE_DATABASE_FIELD_NAME_LEN];

    int mappingTo;

} PEReportFieldMappingInfo;
Members

StructSize | Specifies the size of the PEReportFieldMappingInfo structure. Initialize this member to PE_SIZEOF_REPORT_FIELDMAPPING_INFO.
valueType | Indicates the field value type. The Value Type can be one of the following constants:
 | Constant | Description
 | PE_FVT_INT8SFIELD | 8-bit integer signed
 | PE_FVT_INT8UFIELD | 8-bit integer unsigned
 | PE_FVT_INT16SFIELD | 16-bit integer signed
 | PE_FVT_INT16UFIELD | 16-bit integer unsigned
 | PE_FVT_INT32SFIELD | 32-bit integer signed
 | PE_FVT_INT32UFIELD | 32-bit integer unsigned
 | PE_FVT_NUMBERFIELD | Number field
 | PE_FVT_CURRENCYFIELD | Currency field
 | PE_FVT_BOOLEANFIELD | Boolean field
 | PE_FVT_DATEFIELD | Date field
 | PE_FVT_TIMEFIELD | Time field
 | PE_FVT_STRINGFIELD | String field
 | PE_FVT_TRANSIENTMEMOFIELD | Transient Memo field
 | PE_FVT_PERSISTENTMEMOFIELD | Persistent Memo field
 | PE_FVT_BLOBFIELD | BLOB field
 | PE_FVT_DATETIMEFIELD | Date/Time field
 | PE_FVT_BITMAPFIELD | Bitwise field
 | PE_FVT_ICONFIELD | Icon field
 | PE_FVT_PICTUREFIELD | Picture field
 | PE_FVT_OLEFIELD | OLE field
 | PE_FVT_GRAPHFIELD | Graph field
 | PE_FVT_UNKNOWNFIELD | Unknown field type
tableAliasName | A string (of length PE_TABLE_NAME_LEN = 128) which contains the database table alias name.
databaseFieldName | A string of length (of length PE_DATABASE_FIELD_NAME_LEN = 128) which contains the name of the database field.
mappingTo | An index of a field in an array in the databaseField member of PEFieldMappingEventInfo, which contains the list of database fields. If the field is unmapped then this value is -1.

Delphi Record Listing
type

  PETableAliasNameType = Array [0..PE_TABLE_NAME_LEN -1] of Char;

  PEDatabaseFieldNameType = Array [0..PE_DATABASE_FIELD_NAME_LEN -1]

                                of Char;

  PEReportFieldMappingInfo = record

        StructSize : Word;

        valueType : Word;

        tableAliasName : PETableAliasNameType;

        databaseFieldName : PEDatabaseFieldNameType;

        mappingTo : integer;

        PEFieldMappingEventInfo->databaseFields}

end;


PEReportAlertInfo

PEReportAlertInfo contains information on Report Alerts. This information is used by PEGetNthReportAlert, to retrieve information on the Report Alerts in the report.

C Syntax
typedef struct PEReportAlertInfo
{
    WORD StructSize;
    short nameLength;
    HANDLE name;
    short isEnabled;
    short alertConditionLength;
    HANDLE alertConditionFormula;
    DWORD nTriggeredInstances;
    short alertMessageLength;
    short defaultAlertMessageLength;
    HANDLE alertMessageFormula;
    HANDLE defaultAlertMessage;
} PEReportAlertInfo;
Members

Release the HANDLE even if you are not using it.

StructSize | Specifies the size of the PEReportAlertInfo structure. Initialize this member to PE_SIZEOF_REPORT_ALERT_INFO.
namelenght | Specifies the length of the Report Alert's name.
name | Specifies a handle to the string containing the name of the Report Alert. This is the name assigned to the Report Alert when it was first created.
isEnabled | Specifies wether or not the Report Alert is enabled. Pass TRUE to enable, or PE_UNCHANGED for no change.
alertCondition Lenght | Specifies the length of the condition defined for the Report Alert.
alertCondition Formula | Specifies a handle to the condition formula of the Report Alert. This is the formula created to trigger the Report Alert.
nTriggered Instances | Specifies the number of times a Report Alert was triggered.
alertMessage Lenght | Specifies the length of the conditional message defined for the Report Alert.
defaultAlert MessageLenght | Specifies the length of the default message defined for the Report Alert.
alertMessage Formula | Specifies a handle to the formula used to create the alert message when a Report Alert is triggered.
defaultAlertMessge | Specifies a handle to the default Report Alert message.

VB Type Listing
Type PEReportAlertInfo

    StructSize As Integer

    nameLength As Integer

    name as Long

    isEnabled As Integer

    alertConditionLenght As Integer

    alertConditionFormula As Long

    nTriggeredInstances As Long

    alertMessageLength As Integer

    defaultAlertmessageLength As Integer

    alertMessageFormula As Long

    defaultAlertMessage as Long

End Type
Delphi Record Listing
type PEReportAlertInfo = record
    StructSize : Word;
    nameLength : Smallint;
    name : HWND;
    isEnabled : Smallint;
    alertConditionLength : Smallint;
    alertConditionFormula : HWND;
    nTriggeredInstances : DWord;
    alertMessageLength : SmallInt;
    defaultAlertMessageLength : SmallInt;
    alertMessageFormula : HWND;
    defaultAlertMessage : HWND;
end;


PEReportOptions

PEReportOptions contains report option information. This information is used by PEGetReportOptions, to retrieve current options and by PESetReportOptions, to pass new options.

C Syntax
typedef struct PEReportOptions {

    WORD StructSize;

    short saveDataWithReport;

    short saveSummariesWithReport;

    short useIndexForSpeed;

    short translateDOSStrings;

    short translateDOSMemos;

    short convertDateTimeType;

    short convertNullFieldToDefault;

    short morePrintEngineErrorMessages;

    short caseInsensitiveSQLData;

    short verifyOnEveryPrint;

    short zoomMode;

    short hasGroupTree;

    short dontGenerateDataForHiddenObjects;

    short performGroupingOnServer;

    short doAsyncQuery;

    short promptMode;

    short selectDistinctRecords;
    short alwaysSortLocally;
    short isReadOnly;
    short canSelectDistinctRecords;

}PEReportOptions;
Members

For each member, except as noted below, use TRUE, FALSE, or PE_UNCHANGED for no change.

structSize | Specifies the size of the PEReportOptions structure. Initialize to PE_SIZEOF_REPORT_OPTIONS.
saveDataWithReport | Specifies whether or not data should be saved with the report. Boolean, or PE_UNCHANGED for no change.
saveSummariesWithReport | Specifies whether to save summaries with the report. Boolean, or PE_UNCHANGED for no change.
useIndexForSpeed | Specifies whether or not to use index values. Boolean, or PE_UNCHANGED for no change.
translateDOSStrings | Specifies whether or not to translate DOS strings. Boolean, or PE_UNCHANGED for no change.
translateDOSMemos | Specifies whether or not to translate DOS memos. Boolean, or PE_UNCHANGED for no change.
convertDateTimeType | Specifies whether or not to convert DATE/Time format to another format. Use one of the following constants, or PE_UNCHANGED for no change.
 | Constant | Value
 | PE_RPTOPT_CVTDATETIMETOSTR | 0
 | PE_RPTOPT_CVTDATETIMETODATE | 1
 | PE_RPTOPT_KEEPDATETIMETYPE | 2
convertNullFieldToDefault | Specifies whether or not to convert NULL parameter fields to their default values. Boolean, or PE_UNCHANGED for no change.
morePrintEngineError Messages | Specifies whether or not to allow the print engine to pop up error messages to the screen from an application without the users intervention. Boolean, or PE_UNCHANGED for no change.
caseInsensitiveSQLData | Specifies whether or not to perform a case insensitive search for SQL data. Boolean, or PE_UNCHANGED for no change.
verifyOnEveryPrint | Specifies whether or not to perform database verification for every print job. Boolean, or PE_UNCHANGED for no change.
zoomMode | Use one of the Zoom Level Constants, or PE_UNCHANGED for no change.
hasGroupTree | Specifies whether or not there is a group tree associated with the report. Boolean, or PE_UNCHANGED for no change.
dontGenerateData ForHiddenObjects | Specifies whether or not to generate data for hidden objects. Boolean, or PE_UNCHANGED for no change.
performGroupingOnServer | Specifies whether or not to perform grouping on servers. Boolean, or PE_UNCHANGED for no change.
doAsyncQuery | Boolean, or PE_UNCHANGED for no change.
promptMode | Specifies the prompt mode. Use one of the following constants, or PE_UNCHANGED for no change.
 | Constant | Value | Description
 | PE_RPTOPT_PROMPT_NONE | 0 |
 | PE_RPTOPT_PROMPT_NORMAL | 1 |
 | PE_RPTOPT_PROMPT_ALWAYS | 2 |
selectDistinctRecords | Specifies whether or not to select distinct records. Boolean, or PE_UNCHANGED for no change.
alwaysSortLocally | Specifies whether or not to sort the records locally. Boolean, or PE_UNCHANGED for no change.
isReadOnly | Specifies wether the report is read only. Boolean value. This property is read only.
canSelectDistinctRecords | Specifies wether the report can select distinct records. Boolean value. This property is read only.

VB Type Listing
Type PEReportOptions

    StructSize As Integer

    saveDataWithReport As Integer

    saveSummariesWithReport As Integer

    useIndexForSpeed As Integer

    translateDOSStrings As Integer

    translateDOSMemos As Integer

    convertDateTimeType As Integer

    convertNullFieldToDefault As Integer

    morePrintEngineErrorMessages As Integer

    caseInsensitiveSQLData As Integer

    verifyOnEveryPrint As Integer

    zoomMode As Integer

    hasGroupTree As Integer

    dontGenerateDataForHiddenObjects As Integer

    performGroupingOnServer As Integer

    doAsyncQuery As Integer

    promptMode As Integer

    selectDistinctRecords As Integer

    wysiwygMode As Integer
    alwaysSortLocally as Integer
    isReadOnly as Integer

    canSelectDistinctRecords as Integer

End Type
Delphi Record Listing
type
    PEReportOptions = record
        StructSize : Word;

        saveDataWithReport : Smallint;

        saveSummariesWithReport : Smallint;

        useIndexForSpeed : Smallint;

        translateDOSStrings : Smallint;

        translateDOSMemos : Smallint;

        convertDateTimeType : Smallint;

        convertNullFieldToDefault : Smallint;

        morePrintEngineErrorMessages : Smallint;

        caseInsensitiveSQLData : Smallint;

        verifyOnEveryPrint : Smallint;

        zoomMode : Smallint;

        hasGroupTree : Smallint;

        dontGenerateDataForHiddenObjects : Smallint;    {

        performGroupingOnServer : Smallint;
        alwaysSortLocally : Smallint;
        isReadOnly : Smallint

        canSelectDistinctRecords : Smallint

end;


PEReportSummaryInfo

PEReportSummaryInfo contains report summary information, corresponding to the report summary information in the Crystal Reports Designer.

C Syntax
typedef struct PEReportSummaryInfo {

    WORD StructSize;

    char applicationName[PE_APPLICATION_NAME_LEN];

    char title[PE_TITLE_LEN];

    char subject[PE_SI_SUBJECT_LEN];

    char author[PE_SI_AUTHOR_LEN];

    char keywords[PE_SI_KEYWORDS_LEN];

    char comments[PE_SI_COMMENTS_LEN];

    char reportTemplate[PE_SI_REPORT_TEMPLATE_LEN];

    short savePreviewPicture;

} PEReportSummaryInfo;
Members

StructSize | Specifies the size of the structure. Initialize this member to PE_SIZEOF_REPORT_SUMMARY_INFO.
application Name | Specifies an application name (of length PE_APPLICATION_NAME_LEN = 128) for the application using this report. This member is read only.
title | Specifies the title (of length PE_TITLE_LEN = 128) of the current report.
subject | Specifies the subject (of length PE_SI_SUBJECT_LEN = 128) of the current report.
author | Specifies the (of length PE_SI_AUTHOR_LEN = 128) author of the current report.
keywords | Specifies the keywords (of length PE_SI_KEYWORDS_LEN = 128) included for the current report.
comments | Specifies any comments (of length PE_SI_COMMENTS_LEN = 512) for the current report.
reportTemplate | Specifies the report template (of length PE_SI_REPORT_TEMPLATE_LEN = 128) for the current report.
savePreview Picture | Specifies whether or not to save the preview picture. Boolean or PE_UNCHANGED for no change.

VB Type Listing
Type PEReportSummaryInfo

    StructSize As Integer

    applicationName As String * PE_SI_APPLICATION_NAME_LEN    ' Read only.

    title As String * PE_SI_TITLE_LEN

    subject As String * PE_SI_SUBJECT_LEN

    author As String * PE_SI_AUTHOR_LEN

    keywords As String * PE_SI_KEYWORDS_LEN

    comments As String * PE_SI_COMMENTS_LEN

    reportTemplate As String * PE_SI_REPORT_TEMPLATE_LEN

    savePreviewPicture As Integer

End Type
Delphi Record Listing
type

    PEApplicationNameType

        = array[0..PE_SI_APPLICATION_NAME_LEN-1] of char;

    PETitleType = array[0..PE_SI_TITLE_LEN-1] of char;

    PESubjectType = array[0..PE_SI_SUBJECT_LEN-1] of char;

    PEAuthorType = array[0..PE_SI_AUTHOR_LEN-1] of char;

    PEKeywordsType = array[0..PE_SI_KEYWORDS_LEN-1] of char;
    PECommentsType = array[0..PE_SI_COMMENTS_LEN-1] of char;

    PEReportTemplate

        = array[0..PE_SI_REPORT_TEMPLATE_LEN-1] of char;

    PEReportSummary = record

        StructSize: Integer;

        applicationName: PEApplicationNameType;

        title: PETitleType;

        subject: PESubjectType;

        author: PEAuthorType;

        keywords: PEKeywordsType;

        comments: PEReportTemplate;

    end;


PESearchButtonClickedEventInfo

PESearchButtonClickedEventInfo contains information about a search button clicked event. When the search button is clicked, a callback function will be called with EventId = PE_SEARCH_BUTTON_CLICKED_EVENT.

C Syntax
typedef struct PESearchButtonClickedEventInfo {

    long windowHandle;

    char searchString [PE_SEARCH_STRING_LEN];

    WORD StructSize;

} PESearchButtonClickedEventInfo;
Members

windowHandle | Specifies the handle of the frame window on which the button is placed.
searchString | Search string (of length PE_SEARCH_STRING_LEN = 128) in search edit control.
StructSize | Specifies the size of the PESearchButtonClickedEventInfo structure. Initialize this member to PE_SIZEOF_SEARCH_BUTTON_CLICKED_EVENT_INFO.

VB Type Listing
Type PESearchButtonClickedEventInfo

    windowHandle As Long

    searchString As String * PE_SEARCH_STRING_LEN

    StructSize As Integer

End Type
Delphi Record Listing
type

    PESearchStringType

    = array[0..PE_SEARCH_STRING_LEN-1] of char;

    PESearchButtonClickedEventInfo = record

        windowHandle: longint;

        searchString: PESearchStringType;

        StructSize: Word;

end;


PESectionOptions

PESectionOptions contains specifications for formatting selected report sections and areas. This information is used by the PEGetSectionFormat and PEGetAreaFormat to retrieve current settings and PESetSectionFormat and PESetAreaFormat to pass new settings.

C Syntax
typedef struct PESectionOptions {

    WORD    StructSize;

    WORD    short visible;

    WORD    newPageBefore;

    WORD    newPageAfter;

    WORD    keepTogether;

    WORD    suppressBlankSection;

    WORD    resetPageNAfter;

    WORD    printAtBottomOfPage;

    COLORREF backgroundColor;

    short     underlaySection;

    short     showArea;

    short     freeFormPlacement;

    short     reserveMinimumPageFooter;

} PESectionOptions;
Members

StructSize | Specifies the size of the PESectionOptions structure. Initialize to PE_SIZEOF_SECTION_OPTIONS.
visible | Specifies whether or not the selected section is to be visible. Pass TRUE to keep the section visible, FALSE to hide the section, or PE_UNCHANGED for no change.
newPageBefore | Specifies whether or not the program is to insert a page break before the section is printed. Pass TRUE to insert a page break, FALSE to not insert a page break, or PE_UNCHANGED for no change.
newPageAfter | Specifies whether or not the program is to insert a page break after the section is printed. Pass TRUE to insert a page break, FALSE to not insert a page break, or PE_UNCHANGED for no change.
keepTogether | Specifies whether or not the program is to keep the section together, either on the current page (if there is room) or on the next (if not). Pass TRUE to keep the section together, FALSE to allow the program to split the section data from one page to the next if necessary, or PE_UNCHANGED for no change.
suppressBlank Section | Specifies whether or not the program is to eliminate blank sections from your report. A section must be completely empty before the program suppresses it. Pass TRUE to eliminate the blank sections, FALSE to retain them, or PE_UNCHANGED for no change.
resetPageNAfter | Specifies whether or not the program is to reset the page number to one (1) for the following page, after it prints a group total. Pass TRUE to reset the page number, FALSE to retain the standard numbering, or PE_UNCHANGED for no change.
printAtBottomOf Page | Specifies whether or not the program is to cause each group value to print only at the bottom of a page; FALSE to have the values print in their normal position, or PE_UNCHANGED for no change.
backgroundColor | Specifies the RGB color value contained in the COLORREF value, for section formats only. Use PE_UNCHANGED_COLOR to preserve the existing color or PE_NO_COLOR for no color.
underlaySection | Indicates whether or not the specified section is to underlay the following section(s). TRUE, FALSE, or PE_UNCHANGED for no change.
showArea | Specifies TRUE to show an area, FALSE to hide an area, or PE_UNCHANGED for no change. The user can drill down on a hidden area.
freeFormPlacement | Design time flag. If set to TRUE, an object can be placed anywhere in a section. Use PE_UNCHANGED for no change
reserveMinimum PageFooter | Used to reduce unnecessary white space in the page footer area containing more than one conditionally formatted section. When set to TRUE, the space required to display only one section (the tallest) is reserved. When set to FALSE (default), the maximum height necessary to display every section in the page footer area at full height will be reserved. See Remarks below.

Remarks
  • Not all options are available for all sections or areas. For example, if you select a Page Header or Page Footer section or area, you cannot change newPageBefore or newPageAfter. The only options that are available for all sections are visible and suppressBlankSection.
  • showArea only applies to area format.
  • backgroundColor, underlaySection, showArea, and freeFormPlacement do not apply to area format.
  • reserveMinimumPageFooter can be used to remove undesirable white space when there are two or more sections in the page footer area and only one section, based on conditional settings, will be visible when the report is viewed in the preview window. For example, a report page footer area might contain two sections, one conditionally set to display at the bottom of odd pages and the other at the bottom of even pages. When this member is set to TRUE, sufficient space will be reserved to display only one of the sections included in the area (set to the height of the tallest section). Note that when reserveMinimumPageFooter = TRUE and there is more than one section visible in the page footer area, the visible sections will be displayed only to the extent allowed by the reserved minimum space (the height of the tallest section) with the remainder truncated.
VB Type Listing
Type PESectionOptions

    StructSize As Integer

    Visible As Integer

    NewPageBefore As Integer

    NewPageAfter As Integer

    KeepTogether As Integer

    SuppressBlankSection As Integer

    ResetPageNAfter As Integer

    PrintAtBottomOfPage As Integer

    BackgroundColor As Long

    UnderlaySection As Integer

    ShowArea As Integer

    FreeFormPlacement As Integer

    reserveMinimumPageFooter As Integer

End Type
Delphi Record Listing
type

    PESectionOptions = record

        StructSize: Word;

        visible: Smallint;

        newPageBefore: Smallint;

        newPageAfter: Smallint;

        keepTogether: Smallint;

        suppressBlankSection: Smallint;

        resetPageNAfter: Smallint;

        printAtBottomOfPage: Smallint;

        backgroundColor: COLORREF;

        underlaySection: Smallint;

        showArea: Smallint;

        freeFormPlacement: Smallint;

    end;


PESessionInfo

PESessionInfo contains information about the current Microsoft Access session. Many Microsoft Access database tables require that a session be opened before the table can be used. Use this structure with PEGetNthTableSessionInfo to retrieve current information and PESetNthTableSessionInfo to pass new information.

C Syntax
typedef struct PESessionInfo {

    WORD StructSize;

    char UserID [PE_SESS_USERID_LEN];

    char Password [PE_SESS_PASSWORD_LEN];

    DWORD SessionHandle;

};
Members

StructSize | Specifies the size of the PESessionInfo structure. Initialize this member to PE_SIZEOF_SESSION_INFO.
UserID | Specifies the user ID value (of length PE_SESS_USERID_LEN = 128) needed for logging on to the system.
Password | Specifies the password (of length PE_SESS_PASSWORD_LEN = 128) needed for logging on to the system. Password is undefined when getting information from a report.
SessionHandle | The handle to the current MS Access session. When setting information, if SessionHandle = 0, the UserID and Password settings are used; otherwise the SessionHandle is used. SessionHandle is undefined when getting information from a report.

Remarks

In Microsoft Access 95 and later, an Access database can have session security (also known as user-level security), database-level security, or both.

  • If the Access database contains only session security, simply pass the session password to the Password member before calling PESetNthTableSessionInfo.
  • If the Access database contains database-level security, use a newline character, '\n' (ASCII character 10) followed by the database-level password (for example, "\ndbpassword").
  • If the Access database contains both session security and database-level security, use the session password followed by the newline character and the database password (for example, "sesspswd\ndbpassword").
  • Alternately, database-level security can also be handled by assigning the database-level password to the Password member of PELogOnInfo and calling PESetNthTableLogOnInfo.
VB Type Listing
Type PESessionInfo

    StructSize As Integer

    UserID As String * PE_SESS_USERID_LEN

    Password As String * PE_SESS_PASSWORD_LEN

    SessionHandle As Long

End Type
Delphi Record Listing
type

    PESesPassType = array[1..PE_SESS_PASSWORD_LEN] of char;

    PESessionInfo = record

        StructSize: Word;

        UserID: PESesPassType;

        Password: PESesPassType;

        SessionHandle: DWord;

    end;


PEShowGroupEventInfo

PEShowGroupEventInfo contains information when an event callback is called with event ID equal to PE_SHOW_GROUP_EVENT.

C Syntax
typedef struct PEShowGroupEventInfo {

    WORD StructSize;

    WORD groupLevel;

    long windowHandle;

    char **groupList;

}PEShowGroupEventInfo;
Members

StructSize | Specifies the size of the PEShowGroupEventInfo structure. Initialize this member to PE_SIZEOF_SHOW_GROUP_EVENT_INFO.
groupLevel | The number of the group name in the group list.
windowHandle | Frame window handle where the event happens.
groupList | Specifies a pointer to an array of group names describing the group path to which the group area is going to navigate. This pointer is freed after the callback function.

Remarks

Make a copy of the groupList if you want to keep group path information. CRPE frees the groupList after the callback function.

Delphi Record Listing
type

    PEPCharPointer = ^PChar;

    PEShowGroupEventInfo = record

        StructSize: Word;

        groupLevel: Word;

        windowHandle: Longint;

        groupList: PEPCharPointer;

    end;


PEStartEventInfo

PEStartEventInfo contains start event information when the callback function is called with event ID equal to PE_START_EVENT.

C Syntax
typedef struct PEStartEventInfo {

    WORD StructSize;

    WORD destination;

}PEStartEventInfo;
Members

StructSize | Specifies the size of the PEStartEventInfo structure. Initialize this member to PE_SIZEOF_START_EVENT_INFO.
destination | Specifies the process destination. Uses one of the PE_TO_XXX Job Destination Constants.

VB Type Listing
Type PEStartEventInfo

    StructSize As Integer

    destination As Integer

End Type
Delphi Record Listing
type

    PEStartEventInfo = record

        StructSize: Word;

        destination: Word;

    end;


PEStopEventInfo

PEStopEventInfo contains stop event information when a callback function is called with an event ID equal to PE_STOP_EVENT.

C Syntax
typedef struct PEStopEventInfo {

    WORD StructSize;

    WORD destination;

    WORD jobStatus;

} PEStopEventInfo;
Members

StructSize | Specifies the size of the PEStopEventInfo structure. Initialize this member to PE_SIZEOF_STOP_EVENT_INFO.
destination | Specifies the process destination. Uses one of the PE_TO_XXX Job Destination Constants.
jobStatus | Indicates the current status of the job. Uses one of the PE_JOBXXX Job Status Constants.

VB Type Listing
Type PEStopEventInfo

    StructSize As Integer

    destination As Integer

    jobStatus As Integer

End Type
Delphi Record Listing
type

    PEStopEventInfo  = record

        StructSize: Word;

        destination: Word;

        jobStatus: Word;

    end;


PESubreportInfo

PESubreportInfo contains information about subreports in a report. This structure is used by PEGetSubreportInfo, to gather information about a specified subreport.

C Syntax
typedef struct PESubreportInfo {

    WORD StructSize;

    char name [PE_SUBREPORT_NAME_LEN];

    short NLinks;

    short isOnDemand;

    short external;

    short reimportOption;

} PESubreportInfo;
Members

StructSize | Specifies the size of the PESubreportInfo structure. Initialize this member to PE_SIZEOF_SUBREPORT_INFO.
name | Specifies the string (of length PE_SUBREPORT_NAME_LEN = 128, NULL-terminated) containing the name of the subreport. This is the name assigned to the subreport when it was first created.
NLinks | Specifies the number of links to primary report data.
isOnDemand | TRUE if the subreport is a real-time subreport. FALSE otherwise.
external | TRUE if the subreport is imported. FALSE otherwise.
reimportOption | Specifies the update option for the subreport. Use PE_SRI_ONOPENJOB (reimport the subreport when the main report is opened) or PE_SRI_ONFUNCTIONCALL (reimport the subreport when the API is called).

VB Type Listing
Type PESubreportInfo

    StructSize As Integer

    Name As String * PE_SUBREPORT_NAME_LEN

    NLinks As Integer

    IsOnDemand As Integer

    external As Integer

    reimportOption As Integer

End Type
Delphi Record Listing
type

    PESubreportNameType

    = array[0..PE_SUBREPORT_NAME_LEN-1] of char;

    PESubreportInfo = record

        structSize: Word;

        name: PESubreportNameType;

        NLinks: smallint

        IsOnDemand: smallint

    end;


PETableDifferenceInfo

Read-Only Struct PETableDifferenceInfo contains database table information that is used by PECheckNthTableDifferences.

C Syntax
typedef struct PETableDifferenceInfo {

    WORD StructSize;

    DWORD tableDifferences;

    DWORD reserved1;

    DWORD reserved2;

} PETableDifferenceInfo;
Members

StructSize | Specifies the size of the PETableLocation structure. Initialize this member to PE_SIZEOF_TABLE_DIFFERENCE_INFO.
tableDifferences | Read-Only. Returns any combination of the following PE_TCD_XXX TableDifference Constants.
 | Constant | Value
 | PE_TCD_OKAY | 0x00000000
 | PE_TCD_DATABASENOTFOUND | 0x00000001
 | PE_TCD_SERVERNOTFOUND | 0x00000002
 | PE_TCD_SERVERNOTOPENED | 0x00000004
 | PE_TCD_ALIASCHANGED | 0x00000008
 | PE_TCD_INDEXESCHANGED | 0x00000010
 | PE_TCD_DRIVERCHANGED | 0x00000020
 | PE_TCD_DICTIONARYCHANGED | 0x00000040
 | PE_TCD_FILETYPECHANGED | 0x00000080
 | PE_TCD_RECORDSIZECHANGED | 0x00000100
 | PE_TCD_ACCESSCHANGED | 0x00000200
 | PE_TCD_PARAMETERSCHANGED | 0x00000400
 | PE_TCD_LOCATIONCHANGED | 0x00000800
 | PE_TCD_DATABASEOTHER | 0x00001000
 | PE_TCD_NUMFIELDSCHANGED | 0x00010000
 | PE_TCD_FIELDOTHER | 0x00020000
 | PE_TCD_FIELDNAMECHANGED | 0x00040000
 | PE_TCD_FIELDDESCCHANGED | 0x00080000
 | PE_TCD_FIELDTYPECHANGED | 0x00100000
 | PE_TCD_FIELDSIZECHANGED | 0x00200000
 | PE_TCD_NATIVEFIELDTYPECHANGED | 0x00400000
 | PE_TCD_NATIVEFIELDOFFSETCHANGED | 0x00800000
 | PE_TCD_NATIVEFIELDSIZECHANGED | 0x01000000
 | PE_TCD_FIELDDECPLACESCHANGED | 0x02000000
reserved1 | Reserved. Do not use.
reserved2 | Reserved. Do not use.

VB Type Listing
Type PETableDifferenceInfo

    StructSize As Integer

    tableDifferences As Long

    reserved1 As Long

    reserved2 As Long

End Type
Delphi Record Listing
type

  PETableDifferenceInfo = record

    StructSize       : Word;

    tableDifferences : DWord;

    reserved1        : DWord;

    reserved2        : DWord;

  end;
PETableLocation

PETableLocation contains database location information that is used with the PEGetNthTableLocation to gather current location information and PESetNthTableLocation to pass new location information.

C Syntax
typedef struct PETableLocation {

    WORD StructSize;

    char Location [PE_TABLE_LOCATION_LEN];

    char SubLocation[PE_TABLE_LOCATION_LEN];

    char ConnectBuffer[PE_CONNECTION_BUFFER_LEN];

} PETableLocation;
Members

StructSize | Specifies the size of the PETableLocation structure. Initialize this member to PE_SIZEOF_TABLE_LOCATION.
Location | Specifies the database location (of length PE_TABLE_LOCATION_LEN = 256, NULL-terminated). This member is database dependent and must be formatted correctly for the expected database. The following table lists some examples.
 | Database Location Examples
 | xBASE (Natively): <drive>:\<path>\<file>
 | xBASE (ODBC): <datasource name>
 | Paradox (Natively): <drive>:\<path>\<file>
 | Paradox (ODBC): <datasource name>
 | Btrieve (Natively): <drive>:\<path>\<file>
 | Btrieve (ODBC): <datasource name>
 | Oracle (Natively): <database>.<table>
 | Oracle (ODBC): <database>.<table>
 | SQL Server (Natively): <database>.<owner>.<table>
 | SQL Server (ODBC): <database>.<owner>.<table>
SubLocation | Specifies the database sublocation (of length PE_TABLE_LOCATION_LEN = 256, NULL-terminated).
ConnectBuffer | Specifies the connection buffer (of length PE_CONNECTION_BUFFER_LEN = 512, NULL-terminated) containing connection information for attached tables.

VB Type Listing
Type PETableLocation

    StructSize As Integer

    Location  As String * PE_TABLE_LOCATION_LEN

    SubLocation As String * PE_TABLE_LOCATION_LEN

    ConnectBuffer As String * PE_CONNECTION_BUFFER_LEN

End Type
Delphi Record Listing
type

  PETableLocType = array [0..PE_TABLE_LOCATION_LEN - 1] of Char;

  PEConnectBufferType = array [0..PE_CONNECTION_BUFFER_LEN - 1] of Char;

  PETableLocation = record

    StructSize    : Word;

    Location      : PETableLocType;

    SubLocation   : PETableLocType; { For MS Access Table Names }

    ConnectBuffer : PEConnectBufferType;

  end;


PETablePrivateInfo

PETablePrivateInfo contains information for using data objects such as ADO, RDO, or CDO with the Active Data Driver(PS2MON.DLL).

C Syntax
typedef struct PETablePrivateInfo {

    WORD StructSize;

    WORD nBytes;

    DWORD tag;

    BYTE FAR *dataPtr;

} PETablePrivateInfo;
Members

StructSize | Specifies the size of the PETablePrivateInfo structure. Initialize this member to PE_SIZEOF_TABLE_PRIVATE_INFO.
nBytes | Specifies the length of the data starting at the dataPtr.
tag | Specifies a value indicating the type of data being passed to theDatabaseTable object in the Data parameter. Currently, the only possible value is 3. This value must be used for all Active data sources including DAO, ADO, RDO, CDO, and the Visual Basic data control.
dataPtr | Specifies a pointer to variant data passed to the database driver. With Active data, this must be a Recordset object if DAO, ADO, or the Visual Basic data control is used. If CDO is used, this must be a Rowset object.

Delphi Record Listing
    type

        crBytePointer = ^Byte;

        PETablePrivateInfo = record

                         StructSize: Word;  {initialize to

                                     PE_SIZEOF_TABLE_PRIVATE_INFO}

                             nBytes: Smallint;

                                tag: DWORD;

                            dataPtr: crBytePointer;

        end;


PETableType

PETableType contains information for identifying the type of a specified table. This information is gathered using PEGetNthTableType.

C Syntax
typedef struct PETableType {

    WORD StructSize;

    char DLLName [PE_DLL_NAME_LEN];

    char DescriptiveName [PE_FULL_NAME_LEN];

    WORD DBType;

} PETableType;
Members

StructSize | Specifies the size of the PETableType structure. Initialize this member to PE_SIZEOF_TABLE_TYPE.
DLLName | Specifies the name of the appropriate database DLL (of length PE_DLL_NAME_LEN = 64, NULL-terminated) for the table of interest. Select the DLL you want to use from the table below:
 | Use this DLL | For this standard non-SQL database
 | PDBBDE.DLL | Borland Database Engine
 | PDBBND.DLL | Bound reports
 | PDBDAO.DLL | DAO data sources (Access)
 | PDBJET.DLL | Access
 | PDBPDX.DLL | Paradox
 | PDBXBSE.DLL | dBASE, FoxPro, Clipper
 | PDCTBTRV.DLL | Btrieve
 | PDSDB22.DLL | DB2/2
 | PDSGUPTA.DLL | Gupta
 | PDSNETW.DLL | Netware
 | PDSODBC.DLL | ODBC. See Remarks below.
 | PDSORACL.DLL | Oracle
 | PDSSYB10.DLL | Sybase 10/11
 | PDSSYBAS.DLL | Sybase
DescriptiveName | Specifies the full description of the table of interest (of length PE_FULL_NAME_LEN = 256, NULL-terminated).
DBType | Specifies the type of database that contains the table of interest. Use one of the PE_DT_XXX Database Type Constants.

Remarks

For PDSODBC.DLL, the DescriptiveName includes the ODBC data source name.

VB Type Listing
Type PETableType

    StructSize As Integer

    DLLName As String * PE_DLL_NAME_LEN

    DescriptiveName As String * PE_FULL_NAME_LEN

    DBType As Integer

End Type
Delphi Record Listing
type

    PEDllNameType = array[0..PE_DLL_NAME_LEN-1] of char;

    PEFullNameType = array[0..PE_FULL_NAME_LEN-1] of char;

    PETableType = record

        StructSize: Word;

        DLLName: PEDllNameType;

        DescriptiveName: PEFullNameType;

        DBType: Word;

    end;


PETrackCursorInfo

PETrackCursorInfo is used to retrieve or set the track cursor information for the preview window by using PEGetTrackCursorInfo, and PESetTrackCursorInfo.

C Syntax
typedef struct PETrackCursorInfo {

    WORD StructSize

    short groupAreaCursor;

    short groupAreaFieldCursor;

    short detailAreaCursor;

    short detailAreaFieldCursor;

    short graphCursor;

    long groupAreaCursorHandle;

    long groupAreaFieldCursorHandle;

    long detailAreaCursorHandle;

    long detailAreaFieldCursorHandle;

    long graphCursorHandle;

    short ondemandSubreportCursor;

    short hyperlinkCursor;

} PETrackCursorInfo;
Members
  • Each member of type short can be set to one of the PE_TCD_XXX Track Cursor Constants, or PE_UNCHANGED for no change.
  • Each member of type long is currently reserved and should not be used.

    StructSize

    Specifies the size of the PETrackCursorInfo structure. Initialize this member to PE_SIZEOF_TRACK_CURSOR_INFO.

    groupAreaCursor

    Specifies the group area cursor. Use one of the PE_TC_XXX Track Cursor Constants or PE_UNCHANGED for no change.

    groupAreaFieldCursor

    Specifies the cursor for a memo, blob, database, summary, or formula field in the group area. Use one of the PE_TC_XXX Track Cursor Constants or PE_UNCHANGED for no change.

    detailAreaCursor

    Specifies the Details area cursor. Use one of the PE_TC_XXX Track Cursor Constants or PE_UNCHANGED for no change.

    detailAreaFieldCursor

    Specifies the cursor for a memo, blob, database, summary, or formula field in the Details area. Use one of the PE_TC_XXX Track Cursor Constants or PE_UNCHANGED for no change.

    graphCursor

    Specifies the cursor for the group chart in the Report Header or Report Footer area. Use one of the PE_TC_XXX Track Cursor Constants or PE_UNCHANGED for no change.

    groupAreaCursor
    Handle

    Reserved, do not use.

    groupAreaFiedlCursor
    Handle

    Reserved, do not use.

    detailAreaCursor
    Handle

    Reserved, do not use.

    detailAreaFieldCursor
    Handle

    Reserved, do not use.

    graphCursorHandle

    Reserved, do not use.

    ondemandSubreport
    Cursor

    Specifies the cursor for on-demand subreports when drilldown for the window is enabled. Default is PE_TC_MAGNIFY_CURSOR

    hyperlinkCursor

    Specifies the cursor for hyperlink text in report objects. Default is PE_TC_HAND_CURSOR.

Remarks
  • By default, all the cursors are PE_TC_ARROW_CURSOR. If the canDrillDown option in PEWindowOptions, is True, then groupAreaCursor, groupAreaFieldCursor, and graphCursor will be PE_TC_MAGNIFY_CURSOR.
VB Type Listing
Type PETrackCursorInfo

    groupAreaCursor As Integer

    groupAreaFieldCursor As Integer

    detailAreaCursor As Integer

    detailAreaFieldCursor As Integer

    graphCursor As Integer

    groupAreaCursorHandle As Long

    groupAreaFieldCursorHandle As Long

    detailAreaCursorHandle As Long

    detailAreaFieldCursorHandle As Long

    graphCursorHandle As Long

End Type
Delphi Record Listing
type

    PETrackCursorInfo = record

        StructSize: Word;

        groupAreaCursor: smallint;

        groupAreaFieldCursor: smallint;

        detailAreaCursor: smallint;

        detailAreaFieldCursor: smallint;

        graphCursor: smallint;

        groupAreaCursorHandle:longint;

        groupAreaFieldCursorHandle: longint;

        detailAreaCursorHandle: longint;

        detailAreaFieldCursorHandle: longint;

        graphCursorHandle: longint; {

    end;


PEValueInfo

PEValueInfo contains information that is used by PEConvertPFInfotoVInfo to return converted parameter values in simple types and by PEConvertVInfotoPFInfo to accept values for conversion to the binary format required by PESetNthParameterField.

C Syntax
typedef struct PEValueInfo {

    WORD StructSize;

    WORD valueType;

    double viNumber;

    double viCurrency;

    BOOL viBoolean;

    char viString[PE_VI_STRING_LEN];

    short viDate[3];

    short viDateTime[6];

    short viTime[3];

    COLORREF viColor;

    short viInteger;

    char viC;

    char ignored;

    long viLong

} PEValueInfo;
Members

StructSize | Specifies the size of the PEValueInfo structure. Initialize this member to PE_SIZEOF_VALUE_INFO.
valueType | Specifies the data type of the parameter field. The Crystal Report Engine supports the following data types and associated PE_VI_XXX Value Type constants.
 | Data Type | Constant
 | Number | PE_VI_NUMBER
 | Currency | PE_VI_CURRENCY
 | Boolean | PE_VI_BOOLEAN
 | Date | PE_VI_DATE
 | String | PE_VI_STRING
 | DateTime | PE_VI_DATETIME
 | Time | PE_VI_TIME
 | Integer | PE_VI_INTEGER
 | COLOREF | PE_VI_COLOR
 | Char | PE_VI_CHAR
 | Long | PE_VI_LONG
 | No Value | PE_VI_NOVALUE
viNumber | Specifies the value if the parameter is a numeric value.
viCurrency | Specifies the value if the parameter is a currency value.
viBoolean | Specifies the value if the parameter is a Boolean value.
viString | Specifies the value if the parameter is a string value (of length PE_VI_STRING_LEN = 256).
viDate | Specifies the value if the parameter is a Date value (year, month, day).
viDateTime | Specifies the value if the parameter is a Date/Time value (year, month, day, hour, minute, second).
viTime | Specifies the value if the parameter is a Time value (hour, minute, second).
viColor | Specifies the value if the parameter is a color value.
viInteger | Specifies the value if the parameter is a integer value.
viC | Specifies the value if the parameter is a char value.
ignored | Internal use only for 4 byte alignment. Do not use.
viLong | Specifies the value if the parameter is a long value.

VB Type Listing
Type PEValueInfo

    StructSize As Integer

    valueType As Integer

    viNumber As Double

    viCurrency As Double

    viBoolean As Long

    viString As String * PE_VI_STRING_LEN

    viDate(0 To 2) As Integer

    viDateTime(0 To 5) As Integer

    viTime(0 To 2) As Integer

    viColor As Long

    viInteger As Integer

    viC As Byte

    ignored As Byte

    viLong As Long

End Type
Delphi Record Listing
type

    PEVALUEINFOSTRINGTYPE

    = array[0..PE_VI_STRING_LEN-1] of smallint;

    PEVALUEINFODATEORTIMETYPE = array[0..5] of smallint;

    PEVALUEINFODATETIMETYPE = array[0..2] of smallint;

    PEValueInfo = record

        StructSize:Word;

        valueType: Word; {a PE_VI_constant

        viNumber: Double;

        viCurrency: Double;

        viBoolean: BOOL;

        viString: PEVALUEINFOSTRINGTYPE;

        viDate: PEVALUEINFODATEORTIMETYPE;

        viDateTime: PEVALUEINFODATETIMETYPE;

        viTime: PEVALUEINFODATEORTIMETYPE;

        viColor: COLORREF;

        viInteger: Smallint;

        viC: Char; Char;{BYTE}

        ignored: Char;

        viLong: Longint;

    end;


PEVersionInfo

PEVersionInfo contains information on the version number of the report associated with the job handle. This information is used by PEGetReportVersion, to retrieve major and minor version information on the report.

C Syntax
typedef struct PEVersionInfo
{
    WORD StructSize;
    WORD major;
    WORD minor;
    char letter;
} PEVersionInfo;
Members

StructSize | Specifies the size of the PEVersionInfo structure. Initialize this member to PE_SIZEOF_VERSION_INFO.
major | Specifies the major release number of the report.
minor | Specifies the minor release number of the.report.
letter | Specifies a character value associated with the minor version number of the report. Most reports do not have a character value, so a NULL value will be returned.

VB Type Listing
Type PEVersionInfo

    StructSize As Integer

    major As Integer

    minor As Integer
    letter As String

End Type
Delphi Record Listing
type PEVersionInfo = record
    StructSize : Word;
    major : Word;
    minor : Word;
    character : PChar;
end;


PEWindowOptions

PEWindowOptions contains information related to preview window options. This structure is used by PEGetWindowOptions, and PESetWindowOptions, to get and set preview window contents.

C Syntax
typedef struct PEWindowOptions {

    WORD StructSize;

    short hasGroupTree;

    short canDrillDown;

    short hasNavigationControls;

    short hasCancelButton;

    short hasPrintButton;

    short hasExportButton;

    short hasZoomControl;

    short hasCloseButton;

    short hasProgressControls;

    short hasSearchButton;

    short hasPrintSetupButton;

    short hasRefreshButton;

    short showToolbarTips;

    short showDocumentTips;

short hasLaunchButton;

} PEWindowOptions;
Members

Each member of type short can be set to TRUE, FALSE, or PE_UNCHANGED for no change.

StructSize | Specifies the size of the PEWindowOptions structure. Initialize this member to PE_SIZEOF_WINDOW_OPTIONS.
hasGroupTree | Specifies whether or not the Group Tree will appear in the window. Whether or not the preview window has a group tree is determined by two flags. One is this option (hasGroupTree) and the other is the hasGroupTreeOption in Crystal Reports (File|Report Options dialog box). By default, this value is set to False.
canDrillDown | Specifies whether or not drill-down capabilities will be active in the window. By default, this value is set to False.
hasNavigation Controls | Specifies whether or not navigation controls will appears in the window. By default, this value is set to True.
hasCancelButton | Specifies whether or not a Cancel button will appear in the window. By default, this value is set to True.
hasPrintButton | Specifies whether or not a Print button will appear in the window. By default, this value is set to True.
hasExportButton | Specifies whether or not an Export button will appear in the window By default, this value is set to True.
hasZoomControl | Specifies whether or not zoom controls will appear in the window. By default, this value is set to True.
hasCloseButton | Specifies whether or not a Close button will appear in the window. By default, this value is set to False. If canDrillDown is set to True, CRPE will turnhasCloseButton on unless you set it to False.
hasProgressControls | Specifies whether or not progress controls will appear in the window. By default, this value is set to True.
hasSearchButton | Specifies whether or not a Search button will appear in the window. By default, this value is set to False.
hasPrintSetupButton | Specifies whether or not a Print Setup button will appear in the window.
hasRefreshButton | Specifies whether or not a Refresh button will appear in the window.
showToolbarTips | Specifies whether or not Tooltips are shown on the Toolbar. By default, this value is set to True (default is visible tooltips on toolbar).
showDocumentTips | Specifies whether or not Tooltips are shown on the Document. By default, this value is set to False (default is hidden tooltips on document).
hasLaunchButton | Specifies whether or not a button to launch Seagate Analysis is placed on the toolbar. By default, this value is set to False. Note: Seagate Analysis is now known as Crystal Analysis.

VB Type Listing
Type PEWindowOptions

    StructSize As Integer

    hasGroupTree As Integer

    canDrillDown As Integer

    hasNavigationControls As Integer

    hasCancelButton As Integer

    hasPrintButton As Integer

    hasExportButton As Integer

    hasZoomControl As Integer

    hasCloseButton As Integer

    hasProgressControls As Integer

    hasSearchButton As Integer

    hasPrintSetupButton As Integer

    hasRefreshButton As Integer

    showToolbarTips As Integer

    showDocumentTips As Integer

End Type
Delphi Recor.d Listing
type

    PEWindowOptions = record

        StructSize: Word;

        hasGroupTree: Smallint;

        canDrillDown: Smallint;

        hasNavigationControls: Smallint;

        hasCancelButton: Smallint;

        hasPrintButton: Smallint;

        hasExportButton: Smallint;

        hasZoomControl: Smallint;

        hasCloseButton: Smallint;

        hasProgressControls: Smallint;

        hasSearchButton: Smallint;

        hasPrintSetupButton: Smallint;

        hasRefreshButton: Smallint;

        showToolbarTips: Smallint;

        showDocumentTips:  Smallint;

    end;


PEZoomLevelChangingEventInfo

PEZoomLevelChangingEventInfo contains information about records read
when a callback function is called with event ID equal to PE_ZOOM_LEVEL_CHANGING_EVENT.

C Syntax
typedef struct PEZoomLevelChangingEventInfo {

    WORD StructSize;

    WORD zoomLevel;

    long windowHandle;

} PEZoomLevelChangingEventInfo;
Members

StructSize | Specifies the size of the PEZoomLevelChangingEventInfo structure. Initialize this member to PE_SIZEOF_ZOOM_LEVEL_CHANGNG_EVENT_INFO.
zoomLevel | The zoom level set in the preview window. This can be a value from 25 to 400, indicating a magnification percentage, or it can be one of the Zoom Level Constants.
windowHandle | Specifies the frame window handle where the event happens.

VB Type Listing
Type PEZoomLevelChangingEventInfo

    StructSize As Integer

    zoomLevel As Integer

    windowHandle As Long

End Type
Delphi Record Listing
type

    PEZoomLevelChangingEventInfo = record

        StructSize: Word;

        zoomLevel: Word;

        windowHandle: HWnd;

    end;


UXDDiskOptions

UXDDiskOptions contains file name information that is used by PEEnableEventInfo, when you want to export to a disk file.

C Syntax
struct UXDDiskOptions {

    WORD StructSize;

    char FAR *fileName;

};
Members

structSize | Specifies the size of the UXDDiskOptions structure. You must initialize this member to be the size of whatever it is, for example, options.structSize = UXDDiskOptionsSize.
fileName | Specifies the pointer to the null-terminated string that contains the file name under which you want your disk file saved.

Delphi Record Listing
type

    UXDDiskOptions = record

        structSize: Word;

        fileName: PChar;

    end;


UXDMAPIOptions

UXDMAPIOptions contains e-mail information that is used by PEEnableEventInfo, when you want to export to a MAPI e-mail destination.

C Syntax
struct UXDMAPIOptions {

    WORD StructSize;

    char FAR *toList;

    char FAR *ccList;

    char FAR *subject;

    char FAR *message;

    WORD nRecipients;

    lpMapiRecipDesc recipients;

}
Members

structSize | Specifies the size of the UXDMAPIOptions structure. You must initialize this member to be the size of whatever it is, for example, options.structSize = UXDMAPIOptionsSize.
toList | Specifies the pointer to the null-terminated string that contains the "To" list to which you want your e-mail message directed. If you specify "recipients" in this structure, "toList" is ignored.
ccList | Specifies the pointer to the null-terminated string that contains the "CC" list to which you want your e-mail message copied. This string will appear on the message. If you specify "recipients" in this structure, "ccList" is ignored.
subject | Specifies the pointer to the null-terminated string you want to appear as the subject line in the e-mail message.
message | Specifies the pointer to the null-terminated string you want to appear as the body of your e-mail message.
nRecipients | Specifies the number of recipients that are to receive the e-mail message. You must pass the value "0" if you specify "To" and "CC" lists in this structure.
recipients | Specifies the pointer to an array of structures, each of which describes someone to whom the message is being sent or CC'd. This member is included for those applications that are already using Microsoft's MAPI.DLL. If you are not using MAPI.DLL in your application, there is no advantage to using the recipients array over the toList and ccList. You must pass the value "0" if you specify "To" and "CC" lists in this structure. For detailed information about this member, please refer to Microsoft's MAPI documentation.

Delphi Record Listing
type

    UXDMAPIOptions   = record

        structSize: Word;

        toList: PChar;

        ccList: PChar;

        subject: PChar;

        message: PChar;

    end;


UXDSMIOptions

UXDSMIOptions contains e-mail information that is used by the PEEnableEventInfo, when you want to export to a MAPI e-mail destination.

C Syntax
struct UXDSMIOptions {

    WORD StructSize;

    char FAR *toList;

    char FAR *ccList;

    char FAR *subject;

    char FAR *message;

}
Members

structSize | Specifies the size of the UXDMAPIOptions structure. You must initialize this member to be the size of whatever it is, for example, options.structSize = UXDMAPIOptionsSize.
toList | Specifies the pointer to the null-terminated string that contains the "To" list to which you want your e-mail message directed. If you specify "recipients" in this structure, "toList" is ignored.
ccList | Specifies the pointer to the null-terminated string that contains the "CC" list to which you want your e-mail message copied. This string will appear on the message. If you specify "recipients" in this structure, "ccList" is ignored.
subject | Specifies the pointer to the null-terminated string you want to appear as the subject line in the e-mail message.
message | Specifies the pointer to the null-terminated string you want to appear as the body of your e-mail message.

Delphi Record Listing
type

    UXDSMIOptions   = record

        structSize: Word;

        toList: PChar;

        ccList: PChar;

        subject: PChar;

        message: PChar;

    end;


UXDPostFolderOptions

UXDPostFolderOptions contains information that is used by PEEnableEventInfo, when you want to export to Microsoft Exchange.

C Syntax
struct UXDPostFolderOptions {

    WORD StructSize;

    LPSTR pszProfile;

    LPSTR pszPassword;

    WORD wDestType;

    LPSTR pszFolderPath;

};
Members

structSize | Specifies the size of the UXDPostFolderOptions structure. You must initialize this member to be the size of whatever it is, for example, options.structSize = UXDPostFolderOptionsSize.
pszProfile | Specifies the Exchange profile.
pszPassword | Specifies the Exchange password.
wDestType | Specifies the type of report to export to. Use one of the following:
 | Constant | Valu e | Description
 | UXDExchFolderType | 0 | wDestType for Microsoft Exchange folder.
 | UXDPostDocMessage | 1009 | wDestType for folder messages.
 | UXDPostPersonalReport | 1010 | wDestType for personal report.
 | UXDPostFolderReport | 1011 | wDestType for folder report.
pszFolderPath | Specifies the Exchange path where you want the program to place the exported file.

Delphi Record Listing
type

    UXDPostFolderOptions = record

        structSize:Word;

        pszProfile:PChar;

        pszPassword:PChar;

        wDestType: Word;

        pszFolderPath:PChar;

    end;

(*pszFolderPath has to be in the following format: <Message Store Name>@<Folder Name>@<Folder Name>*)


UXDVIMOptions

UXDVIMOptions contains e-mail message information that is used by PEEnableEventInfo, when you want to export a VIM e-mail destination.

C Syntax
struct UXDVIMOptions {

    WORD StructSize;

    char FAR *toList;

    char FAR *ccList;

    char FAR *bccList

    char FAR *subject;

    char FAR *message;

};

Note: VIM is not supported in the 32-bit version of Crystal Reports.

Members

structSize | Specifies the size of the UXDVIMOptions structure. You must initialize this member to be the size of whatever it is, for example, options.structSize = UXDVIMOptionsSize.
toList | Specifies the pointer to the null-terminated string that contains the "To" list to which you want your e-mail message directed.
ccList | Specifies the pointer to the null-terminated string that contains the "CC" list to which you want your e-mail message copied. This string will appear on the message.
bccList | Specifies the pointer to the null-terminated string that contains the "Blind CC" list to which you want your e-mail message copied. This string will not appear on the message.
subject | Specifies the pointer to the null-terminated string you want to appear as the subject line in the e-mail message.
message | Specifies the pointer to the null-terminated string you want to appear as the body of your e-mail message.


UXFCharSeparatedOptions

UXFCharSeparatedOptions contains number and date information used by the PEEnableEventInfo, structure when you want to export in a Character Separated format and hard code number and/or date options.

C Syntax
struct UXFCharSeparatedOptions {

    WORD StructSize;

    BOOL useReportNumberFormat;

    BOOL useReportDateFormat;

    char stringDelimiter;

    char FAR *fieldDelimiter;

};
Members

structSize | Specifies the size of the UXFCharSeparatedOptions structure. You must initialize this member to be the size of whatever it is, for example, options.structSize = UXFCharSeparatedOptionsSize.
useReport NumberFormat | Indicates whether or not the program should save numbers in the same format (decimal places, negatives, etc.) that you have used in the report. Pass TRUE if you want the program to use the same format used in the report, FALSE if you want the number saved in a format that has been optimized for the file format you have selected.
useReportDate Format | Indicates whether or not the program should save dates in the same format (MDY, DMY, etc.) that you used in the report. Pass TRUE if you want the program to use the same format as used in the report, FALSE if you want dates saved in a format that has been optimized for the file format you have selected.
stringDelimiter | Specifies the character you want to use to enclose alphanumeric field data in the character separated values format. You can use whatever character you wish, and it must be enclosed in quotes.
fieldDelimiter | Specifies a pointer to the string you want to use to separate the fields in the character separated values format. Your string may be up to 16 characters long and must be enclosed in quotes.

Delphi Record Listing
type

    UXFCharSeparatedOptions = record

        structSize: Word;

        useReportNumberFormat: Bool;

        useReportDateFormat: Bool;

        stringDelimiter: Char;

        fieldDelimiter: PChar;

    end;


UXFCommaTabSeparatedOptions

UXFCommaTabSeparatedOptions contains number and date information used by PEEnableEventInfo, when you want to export in a Comma-separated or Tab-separated format and hard code number and/or date options.

C Syntax
struct UXFCommaTabSeparatedOptions {

    WORD StructSize;

    BOOL useReportNumberFormat;

    BOOL useReportDateFormat;

};
Members

structSize | Specifies the size of the UXFCommaTabSeparatedOptions structure. You must initialize this member to be the size of whatever it is, for example, options.structSize = UXFCommaTabSeparatedOptionsSize.
useReport NumberFormat | Indicates whether or not the program should save numbers in the same format (decimal places, negatives, etc.) that you have used in the report. Pass TRUE if you want the program to use the same format used in the report, FALSE if you want the number saved in a format that has been optimized for the file format you have selected.
useReportDate Format | Indicates whether or not the program should save dates in the same format (MDY, DMY, etc.) that you used in the report. Pass TRUE if you want the program to use the same format as used in the report, FALSE if you want dates saved in a format that has been optimized for the file format you have selected.

Delphi Record Listing
type

    UXFCommaTabSeparatedOptions = record

        structSize: Word;

        useReportNumberFormat: Bool;

        useReportDateFormat: Bool;

    end;


UXFDIFOptions

UXFDIFOptions contains number and date information used by PEEnableEventInfo, when you want to export in a DIF format (Data Interchange Format) and hard code number and/or date options.

C Syntax
struct UXFDIFOptions {

    WORD StructSize;

    BOOL useReportNumberFormat;

    BOOL useReportDateFormat;

};
Members

structSize | Specifies the size of the UXFDIFOptions structure. You must initialize this member to be the size of whatever it is, for example, options.structSize = UXFDIFOptionsSize.
useReport NumberFormat | Indicates whether or not the program should save numbers in the same format (decimal places, negatives, etc.) that you have used in the report. Pass TRUE if you want the program to use the same format used in the report, FALSE if you want the number saved in a format that has been optimized for the file format you have selected.
useReport DateFormat | Indicates whether or not the program should save dates in the same format (MDY, DMY, etc.) that you used in the report. Pass TRUE if you want the program to use the same format as used in the report, FALSE if you want dates saved in a format that has been optimized for the file format you have selected.

Delphi Record Listing
type

    UXFDIFOptions = record

        structSize: Word;

        useReportNumberFormat: Bool;

        useReportDateFormat: Bool;

    end;


UXFHTML3Options

UXFHTML3Options contains options used by PEEnableEventInfo, when you are exporting to HTML format.

C Syntax
struct UXFHTML3Options {

    WORD StructSize;

    char FAR *fileName;

};
Members

structSize | Specifies the size of the UXFHTML3Options structure. You must initialize this member to be the size of whatever it is, for example, options.structSize = UXFHTML3OptionsSize.
fileName | Specifies a null terminated file name. For example, "C\pub\docs\boxoffic\default.htm". Any exported GIF files will be located in the same directory as this file.

Delphi Record Listing
type

    UXFHTML3Options = record

        structSize: Word;

        fileName: PChar;

    end;


UXFODBCOptions

UXFODBCOptions contains information used by PEEnableEventInfo, whenever you export in ODBC format.

C Syntax
struct UXFODBCOptions {

    WORD         structSize;

    char FAR     *dataSourceName;

    char FAR     *dataSourceUserID;

    char FAR     *dataSourcePassword;

    char FAR     *exportTableName;

};
Members

structSize | Specifies the size of the UXFODBCOptions structure. You must initialize this member to be the size of whatever it is, for example, options.structSize = UXFODBCOptionsSize.
dataSourceName | Specifies the name of the data source that you want to export to.
dataSourceUserID | Specifies the User ID that you need to connect to the data source.
dataSourcePassword | Specifies the Password that you need to connect to the data source.
exportTableName | Specifies the name of the table you want to export to in the data source.

Delphi Record Listing
type

    UXFODBCOptions = record

        structSize: Word;

        dataSourceName:PChar;

        dataSourceUserID:PChar;

        dataSourcePassword:PChar;

        exportTableName:PChar;

    end;


UXFPaginatedTextOptions

UXFPaginatedTextOptions contains information used by PEEnableEventInfo, whenever you export in paginated text format.

C Syntax
struct UXFPaginatedTextOptions {

    WORD StructSize;

    WORD nLinesPerPage;

};
Members

structSize | Specifies the size of the UXFPaginatedTextOptions structure. Initialize this member to UXFPaginatedTextOptionsSize.
nLines PerPage | Indicates the number of lines to be printed before the page break. The default is 60 lines. When the paginated text format is used with PEGetExportOptions, the program displays the Lines Per Page dialog box to give the user the opportunity to specify a different number if he or she wishes.

Delphi Record Listing
type

    UXFPaginatedTextOptions = Record

        structSize:Word;

        nLinesPerPage:Word;

    end;


UXFRecordStyleOptions

UXFRecordStyleOptions contains number and date information used by PEEnableEventInfo, when you want to export in a Record style (columns of values) format and hard code number and/or date options.

C Syntax
struct UXFRecordStyleOptions {

    WORD StructSize;

    BOOL useReportNumberFormat;

    BOOL useReportDateFormat;

};
Members

structSize | Specifies the size of the UXFRecordStyleOptions structure. Initialize this member to UXFRecordStyleOptionsSize.
useReport NumberFormat | Indicates whether or not the program should save numbers in the same format (decimal places, negatives, etc.) that you have used in the report. Pass TRUE if you want the program to use the same format used in the report, FALSE if you want the number saved in a format that has been optimized for the file format you have selected.
useReport DateFormat | Indicates whether or not the program should save dates in the same format (MDY, DMY, etc.) that you used in the report. Pass TRUE if you want the program to use the same format as used in the report, FALSE if you want dates saved in a format that has been optimized for the file format you have selected.

Delphi Record Listing
type

    UXFRecordStyleOptions = record

        structSize: Word;

        useReportNumberFormat: Bool;

        useReportDateFormat: Bool;

    end;


Microsoft Windows Structures

The COLORREF and DEVMODE structures are discussed in this section.


COLORREF

Microsoft Windows COLORREF (Windef.h) is a 32-bit value used to specify an RGB color.

Syntax

When specifying an explicit RGB color, COLORREF has the following hexadecimal form:

    0x00bbggrr

where the low-order byte (rr) contains a value for the relative intensity of red, the second byte (gg) contains a value for green, and the third byte (bb) contains a value for blue. The high-order byte must be zero. The maximum value for a single byte is 0xFF.

Remarks

Complete documentation for the COLORREF Microsoft Windows value can be found at
http://msdn.microsoft.com/


DEVMODE

The Microsoft Windows DEVMODE structures contain information about the device initialization and environment of a printer.

C Syntax
typedef struct _devicemode {

    BCHAR  dmDeviceName[CCHDEVICENAME];

    WORD   dmSpecVersion;

    WORD   dmDriverVersion;

    WORD   dmSize;

    WORD   dmDriverExtra;

    DWORD  dmFields;

    union {

       struct {

        short dmOrientation;

        short dmPaperSize;

        short dmPaperLength;

        short dmPaperWidth;

       };

       POINTL dmPosition;

    };

    short  dmScale;

    short  dmCopies;

    short  dmDefaultSource;

    short  dmPrintQuality;

    short  dmColor;

    short  dmDuplex;

    short  dmYResolution;

    short  dmTTOption;

    short  dmCollate;

    BCHAR  dmFormName[CCHFORMNAME];

    WORD  dmLogPixels;

    DWORD  dmBitsPerPel;

    DWORD  dmPelsWidth;

    DWORD  dmPelsHeight;

    DWORD  dmDisplayFlags;

    DWORD  dmDisplayFrequency;

  #if(WINVER >= 0x0400)

    DWORD  dmICMMethod;

    DWORD  dmICMIntent;

    DWORD  dmMediaType;

    DWORD  dmDitherType;

    DWORD  dmReserved1;

    DWORD  dmReserved2;

  #if (WINVER >= 0x0500) || (_WIN32_WINNT >= 0x0400)

    DWORD  dmPanningWidth;

    DWORD  dmPanningHeight;

  #endif /* WINVER >= 0x0500 */

  #endif /* WINVER >= 0x0400 */

} DEVMODE;
Members

dmDeviceName | Specifies the name of the device the driver supports (for example, PCL/HP LaserJet for PCL/HP LaserJet®). This string is unique among device drivers.
dmSpecVersion | Specifies the version number of the initialization data specification on which the structure is based.
dmDriverVersion | Specifies the printer driver version number assigned by the printer driver developer.
dmSize | Specifies the size, in bytes, of the DEVMODE structure except the dmDriverData (device-specific) member. If an application manipulates only the driver-independent portion of the data, it can use this member to determine the length of the structure without having to account for different versions.
dmDriverExtra | Contains the number of bytes of private driver-data that follow this structure. If a device driver does not use device-specific information, set this member to zero. See Remarks below.
dmFields | Specifies which of the remaining members in the DEVMODE structure have been initialized. Bit 0 (defined as DM_ORIENTATION) corresponds to dmOrientation; bit 1 (defined as DM_PAPERSIZE) specifies dmPaperSize, and so on. A printer driver supports only those members that are appropriate for the printer technology.
dmOrientation | Selects the orientation of the paper. This member can be set to either of the following:
Constant | Description
DMORIENT_PORTRAIT |
DMORIENT_LANDSCAPE |

dmPaperSize

Selects the size of the paper to print on. This member can be set to zero if the length and width of the paper are both set by the dmPaperLength and dmPaperWidth members. Otherwise, the dmPaperSize member can be set to one of the following predefined values:

Constant | Description
DMPAPER_LETTER | Letter, 8 1/2 by 11 inches
DMPAPER_LEGAL | Legal, 8 1/2 by 14 inches
DMPAPER_A4 A4 | Sheet, 210 by 297 millimeters
DMPAPER_CSHEET | C Sheet, 17 by 22 inches
DMPAPER_DSHEET | D Sheet, 22 by 34 inches
DMPAPER_ESHEET | E Sheet, 34 by 44 inches
DMPAPER_LETTERSMALL | Letter Small, 8 1/2 by 11 inches
DMPAPER_TABLOID | Tabloid, 11 by 17 inches
DMPAPER_LEDGER | Ledger, 17 by 11 inches
DMPAPER_STATEMENT | Statement, 5 1/2 by 8 1/2 inches
DMPAPER_EXECUTIVE | Executive, 7 1/4 by 10 1/2 inches
DMPAPER_A3 | A3 sheet, 297 by 420 millimeters
DMPAPER_A4SMALL | A4 small sheet, 210 by 297 millimeters
DMPAPER_A5 | A5 sheet, 148 by 210 millimeters
DMPAPER_B4 | B4 sheet, 250 by 354 millimeters
DMPAPER_B5 | B5 sheet, 182-by-257-millimeter paper
DMPAPER_FOLIO | Folio, 8-1/2-by-13-inch paper
DMPAPER_QUARTO | Quarto, 215-by-275-millimeter paper
DMPAPER_10X14 | 10-by-14-inch sheet
DMPAPER_11X17 | 11-by-17-inch sheet
DMPAPER_NOTE | Note, 8 1/2 by 11 inches
DMPAPER_ENV_9 | #9 Envelope, 3 7/8 by 8 7/8 inches
DMPAPER_ENV_10 | #10 Envelope, 4 1/8 by 9 1/2 inches
DMPAPER_ENV_11 | #11 Envelope, 4 1/2 by 10 3/8 inches
DMPAPER_ENV_12 | #12 Envelope, 4 3/4 by 11 inches
DMPAPER_ENV_14 | #14 Envelope, 5 by 11 1/2 inches
DMPAPER_ENV_DL | DL Envelope, 110 by 220 millimeters
DMPAPER_ENV_C5 | C5 Envelope, 162 by 229 millimeters
DMPAPER_ENV_C3 | C3 Envelope, 324 by 458 millimeters
DMPAPER_ENV_C4 | C4 Envelope, 229 by 324 millimeters
DMPAPER_ENV_C6 | C6 Envelope, 114 by 162 millimeters
DMPAPER_ENV_C65 | C65 Envelope, 114 by 229 millimeters
DMPAPER_ENV_B4 | B4 Envelope, 250 by 353 millimeters
DMPAPER_ENV_B5 | B5 Envelope, 176 by 250 millimeters
DMPAPER_ENV_B6 | B6 Envelope, 176 by 125 millimeters
DMPAPER_ENV_ITALY | Italy Envelope, 110 by 230 millimeters
DMPAPER_ENV_ MONARCH | Monarch Envelope, 3 7/8 by 7 1/2 inches
DMPAPER_ENV_ PERSONAL | 6 3/4 Envelope, 3 5/8 by 6 1/2 inches
DMPAPER_FANFOLD_US | US Std Fanfold, 14 7/8 by 11 inches
DMPAPER_FANFOLD_ STD_GERMAN | German Std Fanfold, 8 1/2 by 12 inches
DMPA PER_FANFOLD_ LGL_GERMAN | German Legal Fanfold, 8 1/2 by 13 inches
dmPaperLength | Overrides the length of the paper specified by the dmPaperSize member, either for custom paper sizes or for devices such as dot-matrix printers, which can print on a page of arbitrary length. These values, along with all other values in this structure that specify a physical length, are in tenths of a millimeter.
dmPaperWidth | Overrides the width of the paper specified by the dmPaperSize member.
dmScale | Specifies the factor by which the printed output is to be scaled. The apparent page size is scaled from the physical page size by a factor of dmScale/100. For example, a letter-sized page with a dmScale value of 50 would contain as much data as a page of 17 by 22 inches because the output text and graphics would be half their original height and width.
dmCopies | Selects the number of copies printed if the device supports multiple-page copies.
dmDefaultSource | Reserved. This member must be set to 0.
dmPrintQuality | Specifies the printer resolution. There are four predefined device-independent values. If a positive value is given, it specifies the number of dots per inch (DPI) and is therefore device dependent.
Constant | Description
DMRES_HIGH |
DMRES_MEDIUM |
DMlRES_LOW |
DMRES_DRAFT |

dmColor

Switches between color and monochrome on color printers. Following are the possible values:

Constant | Description
DMCOLOR_COLOR |
DMCOLOR_MONOCHROME |

dmDuplex

Selects duplex or double-sided printing for printers capable of duplex printing. Following are the possible values:

Constant | Description
DMDUP_SIMPLEX |
DMDUP_HORIZONTAL |
DMDUP_VERTICAL |
dmYResolution | Specifies the y-resolution, in dots per inch, of the printer. If the printer initializes this member, the dmPrintQuality member specifies the x-resolution, in dots per inch, of the printer.
dmTTOption | Specifies how TrueType® fonts should be printed. This member can be one of the following values:
Constant | Description
DMTT_BITMAP | Prints TrueType fonts as graphics. This is the default action for dot-matrix printers.
DMTT_DOWNLOAD | Downloads TrueType fonts as soft fonts. This is the default action for Hewlett-Packard printers that use Printer Control Language (PCL).
DMTT_SUBDEV | Substitute device fonts for TrueType fonts. This is the default action for PostScript® printers.

dmCollate

Specifies whether collation should be used when printing multiple copies. Using DMCOLLATE_FALSE provides faster, more efficient output, since the data is sent to a page printer just once, no matter how many copies are required. The printer is told to simply print the page again. This member can be be one of the following values:

Constant | Description
DMCOLLATE_TRUE | Collate when printing multiple copies.
DMCOLLATE_FALSE | Do NOT collate when printing multiple copies.
dmFormName | Specifies the name of the form to use; for example, Letter or Legal. A complete set of names can be retrieved through the Windows EnumForms function.
dmUnusedPadding | Used to align the structure to a DWORD boundary. This should not be used or referenced. Its name and usage is reserved, and can change in future releases.
dmBitsPerPel | Specifies in bits per pixel the color resolution of the display device. For example: 4 bits for 16 colors, 8 bits for 256 colors, or 16 bits for 65,536 colors.
dmPelsWidth | Specifies the width, in pixels, of the visible device surface.
dmPelsHeight | Specifies the height, in pixels, of the visible device surface.
dmDisplayFlags | Specifies the device's display mode. The following are valid flags:
Constant | Description
DM_GRAYSCALE | Specifies that the display is a non-color device. If this flag is not set, color is assumed.
DM_INTERLACED | Specifies that the display mode is interlaced. If the flag is not set, non-interlaced is assumed.
dmDisplay Frequency | Specifies the frequency, in hertz (cycles per second), of the display device in a particular mode.
dmICMMethod | Specifies how ICM is handled. For a non-ICM application, this member determines if ICM is enabled or disabled. For ICM applications, the system examines this member to determine how to handle ICM support. The printer driver must provide a user interface for setting this member. Most printer drivers support only the DMICMMETHOD_SYSTEM or DMICMMETHOD_NONE value. Drivers for PostScript printers support all values. This member can be one of the following predefined values, or a driver-defined value greater than or equal to the value of DMICMMETHOD_USER.
Constant | Description
DMICMMETHOD_NONE | Specifies that ICM is disabled.
DMICMMETHOD_SYSTEM | Specifies that ICM is handled by Windows.
DMICMMETHOD_DRIVER | Specifies that ICM is handled by the device driver.
DMICMMETHOD_DEVICE | Specifies that ICM is handled by the destination device.

dmICMIntent

Windows 95/98, Windows 2000: Specifies which of the three possible color matching methods, or intents, should be used by default. This member is primarily for non-ICM applications. ICM applications can establish intents by using the ICM functions. This member can be one of the following predefined values, or a driver defined value greater than or equal to the value of DMICM_USER.

Constant | Description
DMICM_ABS_ COLORIMETRIC | Color matching should optimize to match the exact color requested without white point mapping. This value is most appropriate for use with proofing.
DMICM_COLORMETRIC | Color matching should optimize to match the exact color requested. This value is most appropriate for use with business logos or other images when an exact color match is desired.
DMICM_CONTRAST | Color matching should optimize for color contrast. This value is the most appropriate choice for scanned or photographic images when dithering is desired.
DMICM_SATURATE | Color matching should optimize for color saturation. This value is the most appropriate choice for business graphs when dithering is not desired.

dmMediaType

Windows 95/98, Windows 2000: Specifies the type of media being printed on. The member can be one of the following predefined values, or a driver-defined value greater than or equal to the value of DMMEDIA_USER.

Constant | Description
DMMEDIA_STANDARD | Plain paper.
DMMEDIA_GLOSSY | Glossy paper.
DMMEDIA_TRANSPARENCY | Transparent film.

dmDitherType

Windows 95/98, Windows 2000: Specifies how dithering is to be done. The member can be one of the following predefined values, or a driver-defined value greater than or equal to the value of DMDITHER_USER.

Constant | Description
DMDITHER_NONE | No dithering.
DMDITHER_COARSE | Dithering with a coarse brush.
DMDITHER_FINE | Dithering with a fine brush.
DMDITHER_LINEART | Line art dithering, a special dithering method that produces well defined borders between black, white, and gray scalings. It is not suitable for images that include continuous graduations in intensisty and hue such as scanned photographs.
DMDITHER_ ERRORDIFFUSION | Windows 95/98: Dithering in which an algorithm is used to spread, or diffuse, the error of approximating a specified color over adjacent pixels. In contrast, DMDITHER_COARSE, DMDITHER_FINE, and DMDITHER_LINEART use patterned halftoning to approximate a color.
DMDITHER_GRAYSCALE | Device does grayscaling.
dmReserved1 | Windows 95/98, Windows 2000: Not used; must be zero.
dmReserved2 | Windows 95/98, Windows 2000: Not used; must be zero.
dmPanningWidth | Windows NT/Windows 2000: This member must be zero. Windows 95/98: This member is not supported.
dmPanningHeight | Windows NT/Windows 2000: This member must be zero. Windows 95/98: This member is not supported.

Remarks
  • Header file: Wingdi.h
  • A device driver's private data follows the public portion of the DEVMODE structure. The size of the public data can vary for different versions of the structure. The dmSize member specifies the number of bytes of public data, and the dmDriverExtra member specifies the number of bytes of private data.
  • Complete documentation for the DEVMODE Microsoft Windows API structures can be found at
    http://msdn.microsoft.com/


Print Engine Constants

The Print Engine constants are listed alphabetically in this section.

  • Area/Section Format Formula Constants
  • Chart Options Constants
  • Graph Subtype Constants
  • Graph Text Font Constants
  • Graph Title Type Constants
  • Graph Type Constants
  • Group Condition Constants
  • Job Destination Constants
  • Job Status Constants
  • Object Type Constants
  • Ole Object Type Constants
  • Ole Object Update Constants
  • Parameter Field Value Type Constants
  • Range Info Constants
  • Section Codes
  • Sort Method Constants
  • Sort Order Constants
  • Track Cursor Constants
  • Zoom Level Constants


Area/Section Format Formula Constants

Constants PE_FFN_SECTION_VISIBILITY and PEP_FFN_SECTION_BACK_COLOUR are included for support of older applications. These constants has the same value as PE_FFN_AREASECTION_VISIBILITY and PEP_FFN_SECTION_BACK_COLOR. All new Crystal Reports applications should use PE_FFN_AREASECTION_VISIBILITY and PEP_FFN_SECTION_BACK_COLOR.

Constant | Description
PE_FFN_AREASECTION_VISIBILITY | Area and Section format
PE_FFN_SECTION_VISIBILITY | Section format
PE_FFN_SHOW_AREA | Area format
PE_FFN_NEW_PAGE_BEFORE | Area and Section format
PE_FFN_NEW_PAGE_AFTER | Area and Section format
PE_FFN_KEEP_TOGETHER | Area and Section format
PE_FFN_SUPPRESS_BLANK_SECTION | Section format
PE_FFN_RESET_PAGE_N_AFTER | Area and Section format
PE_FFN_PRINT_AT_BOTTOM_OF_PAGE | Area and Section format
PE_FFN_UNDERLAY_SECTION | Section format
PE_FFN_SECTION_BACK_COLOUR | Section format
PE_FFN_SECTION_BACK_COLOR | Section format


Chart Options Constants

The following chart options constants are supported.

Chart Bar Size Constants

Chart Color Constants

Chart Data Point Constants

Chart Gridline Constants

Chart Legend Layout Constants

Chart Legend Placement Constants

Chart Marker Shape Constants

Chart Marker Size Constants

Chart Number Format Constants

Chart Pie Size Constants

Chart Slice Detachment Constants

Chart Viewing Angle Constants


Chart Bar Size Constants

Constant

PE_GBS_MINIMUMBARSIZE

PE_GBS_SMALLBARSIZE

PE_GBS_AVERAGEBARSIZE

PE_GBS_LARGEBARSIZE

PE_GBS_MAXIMUMBARSIZE


Chart Color Constants

Constant

PE_GCR_COLORCHART

PE_GCR_BLACKANDWHITECHART


Chart Data Point Constants

Constant

PE_GDP_NONE

PE_GDP_SHOWLABEL

PE_GDP_SHOWVALUE


Chart Gridline Constants

Constant

PE_GGT_NOGRIDLINES

PE_GGT_MINORGRIDLINES

PE_GGT_MAJORGRIDLINES

PE_GGT_MAJORANDMINORGRIDLINES


Chart Legend Layout Constants

Constant | Description
PE_GLL_PERCENTAGE |
PE_GLL_AMOUNT |
PE_GLL_CUSTOM | Used for PEGetGraphOptionInfo only. Do not use for PESetGraphOptionInfo.


Chart Legend Placement Constants

Constant

PE_GLP_PLACEUPPERRIGHT

PE_GLP_PLACEBOTTOMCENTER

PE_GLP_PLACETOPCENTER

PE_GLP_PLACERIGHT

PE_GLP_PLACELEFT


Chart Marker Shape Constants

Constant

PE_GMSP_RECTANGLESHAPE

PE_GMSP_CIRCLESHAPE

PE_GMSP_DIAMONDSHAPE

PE_GMSP_TRIANGLESHAPE


Chart Marker Size Constants

Constant

PE_GMS_SMALLMARKERS

PE_GMS_MEDIUMSMALLMARKERS

PE_GMS_MEDIUMMARKERS

PE_GMS_MEDIUMLARGEMARKERS

PE_GMS_LARGEMARKERS


Chart Number Format Constants

Constant

PE_GNF_NODECIMAL

PE_GNF_ONEDECIMAL

PE_GNF_TWODECIMAL

PE_GNF_CURRENCYNODECIMAL

PE_GNF_CURRENCYTWODECIMAL

PE_GNF_PERCENTNODECIMAL

PE_GNF_PERCENTONEDECIMAL

PE_GNF_PERCENTTWODECIMAL


Chart Pie Size Constants

Constant

PE_GPS_MINIMUMPIESIZE

PE_GPS_SMALLPIESIZE

PE_GPS_AVERAGEPIESIZE

PE_GPS_LARGEPIESIZE

PE_GPS_MAXIMUMPIESIZE


Chart Slice Detachment Constants

Constant

PE_GDPS_NODETACHMENT

PE_GDPS_SMALLESTSLICE

PE_GDPS_LARGESTSLICE


Chart Viewing Angle Constants

Constant

PE_GVA_STANDARDVIEW

PE_GVA_TALLVIEW

PE_GVA_TOPVIEW

PE_GVA_DISTORTEDVIEW

PE_GVA_SHORTVIEW

PE_GVA_GROUPEYEVIEW

PE_GVA_GROUPEMPHASISVIEW

PE_GVA_FEWSERIESVIEW

PE_GVA_FEWGROUPSVIEW

PE_GVA_DISTORTEDSTDVIEW

PE_GVA_THICKGROUPSVIEW

PE_GVA_SHORTERVIEW

PE_GVA_THICKSERIESVIEW

PE_GVA_THICKSTDVIEW

PE_GVA_BIRDSEYEVIEW

PE_GVA_MAXVIEW


Database Type Constants

Constant | Description
PE_DT_STANDARD | Standard, non-SQL databases.
PE_DT_SQL | SQL databases.
PE_DT_SQL_STORED_PROCEDURE | SQL stored procedures.


Error Codes

Constant | Value | Description
PE_ERR_NOERROR | 0 |
PE_ERR_NOTENOUGHMEMORY | 500 |
PE_ERR_INVALIDJOBNO | 501 |
PE_ERR_INVALIDHANDLE | 502 |
PE_ERR_STRINGTOOLONG | 503 |
PE_ERR_NOSUCHREPORT | 504 |
PE_ERR_NODESTINATION | 505 |
PE_ERR_BADFILENUMBER | 506 |
PE_ERR_BADFILENAME | 507 |
PE_ERR_BADFIELDNUMBER | 508 |
PE_ERR_BADFIELDNAME | 509 |
PE_ERR_BADFORMULANAME | 510 |
PE_ERR_BADSORTDIRECTION | 511 |
PE_ERR_ENGINENOTOPEN | 512 |
PE_ERR_INVALIDPRINTER | 513 |
PE_ERR_PRINTFILEEXISTS | 514 |
PE_ERR_BADFORMULATEXT | 515 |
PE_ERR_BADGROUPSECTION | 516 |
PE_ERR_ENGINEBUSY | 517 |
PE_ERR_BADSECTION | 518 |
PE_ERR_NOPRINTWINDOW | 519 |
PE_ERR_JOBALREADYSTARTED | 520 |
PE_ERR_BADSUMMARYFIELD | 521 |
PE_ERR_NOTENOUGHSYSRES | 522 |
PE_ERR_BADGROUPCONDITION | 523 |
PE_ERR_JOBBUSY | 524 |
PE_ERR_BADREPORTFILE | 525 |
PE_ERR_NODEFAULTPRINTER | 526 |
PE_ERR_SQLSERVERERROR | 527 |
PE_ERR_BADLINENUMBER | 528 |
PE_ERR_DISKFULL | 529 |
PE_ERR_FILEERROR | 530 |
PE_ERR_INCORRECTPASSWORD | 531 |
PE_ERR_BADDATABASEDLL | 532 |
PE_ERR_BADDATABASEFILE | 533 |
PE_ERR_ERRORINDATABASEDLL | 534 |
PE_ERR_DATABASESESSION | 535 |
PE_ERR_DATABASELOGON | 536 |
PE_ERR_DATABASELOCATION | 537 |
PE_ERR_BADSTRUCTSIZE | 538 |
PE_ERR_BADDATE | 539 |
PE_ERR_BADEXPORTDLL | 540 |
PE_ERR_ERRORINEXPORTDLL | 541 |
PE_ERR_PREVATFIRSTPAGE | 542 |
PE_ERR_NEXTATLASTPAGE | 543 |
PE_ERR_CANNOTACCESSREPORT | 544 |
PE_ERR_USERCANCELLED | 545 |
PE_ERR_OLE2NOTLOADED | 546 |
PE_ERR_BADCROSSTABGROUP | 547 |
PE_ERR_NOCTSUMMARIZEDFIELD | 548 |
PE_ERR_DESTINATIONNOTEXPORT | 549 |
PE_ERR_INVALIDPAGENUMBER | 550 |
PE_ERR_NOTSTOREDPROCEDURE | 552 |
PE_ERR_INVALIDPARAMETER | 553 |
PE_ERR_GRAPHNOTFOUND | 554 |
PE_ERR_INVALIDGRAPHTYPE | 555 |
PE_ERR_INVALIDGRAPHDATA | 556 |
PE_ERR_CANNOTMOVEGRAPH | 557 |
PE_ERR_INVALIDGRAPHTEXT | 558 |
PE_ERR_INVALIDGRAPHOPT | 559 |
PE_ERR_BADSECTIONHEIGHT | 560 |
PE_ERR_BADVALUETYPE | 561 |
PE_ERR_INVALIDSUBREPORTNAME | 562 |
PE_ERR_NOPARENTWINDOW | 564 | Dialog parent window
PE_ERR_INVALIDZOOMFACTOR | 565 | Zoom factor
PE_ERR_PAGESIZEOVERFLOW | 567 |
PE_ERR_LOWSYSTEMRESOURCES | 568 |
PE_ERR_INVALIDOBJECTFORMATNAME | 571 |
PE_ERR_INVALIDNEGATIVEVALUE | 572 |
PE_ERR_INVALIDMEMORYPOINTER | 573 |
PE_ERR_INVALIDOBJECTTYPE | 574 |
PE_ERR_INVALIDGRAPHDATATYPE | 577 |
PE_ERR_INVALIDSUBREPORTLINKNUMBER | 582 |
PE_ERR_SUBREPORTLINKEXIST | 583 |
PE_ERR_BADROWCOLVALUE | 584 |
PE_ERR_INVALIDSUMMARYNUMBER | 585 |
PE_ERR_INVALIDGRAPHDATAFIELDNUMBER | 586 |
PE_ERR_INVALIDSUBREPORTNUMBER | 587 |
PE_ERR_INVALIDFIELDSCOPE | 588 |
PE_ERR_FIELDINUSE | 590 |
PE_ERR_INVALIDPARAMETERNUMBER | 594 |
PE_ERR_INVALIDPAGEMARGINS | 595 |
PE_ERR_REPORTONSECUREQUERY | 596 |
PE_ERR_CANNOTOPENSECUREQUERY | 597 |
PE_ERR_INVALIDSECTIONNUMBER | 598 |
PE_ERR_SQLSERVERNOTOPENED | 599 |
PE_ERR_TABLENAMEEXIST | 606 |
PE_ERR_INVALIDCURSOR | 607 |
PE_ERR_FIRSTPASSNOTFINISHED | 608 |
PE_ERR_CREATEDATASOURCE | 609 |
PE_ERR_CREATEDRILLDOWNPARAMETERS | 610 |
PE_ERR_CHECKFORDATASOURCECHANGES | 613 |
PE_ERR_STARTBACKGROUNDPROCESSING | 614 |
PE_ERR_SQLSERVERINUSE | 619 |
PE_ERR_GROUPSORTFIELDNOTSET | 620 |
PE_ERR_CANNOTSETSAVESUMMARIES | 621 |
PE_ERR_LOADOLAPDATABASEMANAGER | 622 |
PE_ERR_OPENOLAPCUBE | 623 |
PE_ERR_READOLAPCUBEDATA | 624 |
PE_ERR_CANNOTSAVEQUERY | 626 |
PE_ERR_CANNOTREADQUERYDATA | 627 |
PE_ERR_MAINREPORTFIELDLINKED | 629 |
PE_ERR_INVALIDMAPPINGTYPEVALUE | 630 |
PE_ERR_HITTESTFAILED | 636 |
PE_ERR_BADSQLEXPRESSIONNAME | 637 | No SQL expression by the specified *name* exists in this report.
PE_ERR_BADSQLEXPRESSIONNUMBER | 638 | No SQL expression by the specified *number* exists in this report.
PE_ERR_BADSQLEXPRESSIONTEXT | 639 | Not a valid SQL expression
PE_ERR_INVALIDDEFAULTVALUEINDEX | 641 | Invalid index for default value of a parameter.
PE_ERR_NOMINMAXVALUE | 642 | The specified PE_PF_* type does not have min/max values.
PE_ERR_INCONSISTANTTYPES | 643 | If both min and max values are specified in PESetParameterMinMaxValue, the value types for the min and max must be the same.
PE_ERR_CANNOTLINKTABLES | 645 |
PE_ERR_CREATEROUTER | 646 |
PE_ERR_INVALIDFIELDINDEX | 647 |
PE_ERR_INVALIDGRAPHTITLETYPE | 648 |
PE_ERR_INVALIDGRAPHTITLEFONTTYPE | 649 |
PE_ERR_PARAMTYPEDIFFERENT | 650 | The type used in a add/set value API for a parameter differs with it's existing type.
PE_ERR_INCONSISTANTRANGETYPES | 651 | The value type for both start & end range values must be the same.
PE_ERR_RANGEORDISCRETE | 652 | An operation was attempted on a discrete parameter that is only legal for range parameters or vice versa.
PE_ERR_NOTMAINREPORT | 654 | An operation was attempted that is disallowed for subreports.
PE_ERR_INVALIDCURRENTVALUEINDEX | 655 | Invalid index for current value of a parameter.
PE_ERR_LINKEDPARAMVALUE | 656 | Operation illegal on linked parameter.
PE_ERR_INVALIDPARAMETERRANGEINFO | 672 | Invalid PE_RI_XXX combination.
PE_ERR_INVALIDSORTMETHODINDEX | 674 | Invalid sort method index.
PE_ERR_INVALIDGRAPHSUBTYPE | 675 | Invalid PE_GST_XXX or PE_GST_XXX does not match PE_GT_XXX or PE_GST_XXX current graph type.
PE_ERR_BADGRAPHOPTIONINFO | 676 | One of the members of PEGraphOptionInfo is out of range.
PE_ERR_BADGRAPHAXISINFO | 677 | One of the members of PEGraphAxisInfo is out of range.
PE_ERR_INVALIDPARAMETERVALUE | 687 |
PE_ERR_INVALIDFORMULASYNTAXTYPE | 688 | Specified formula syntax not in PE_FST_XXX
PE_ERR_INVALIDCROPVALUE | 689 |
PE_ERR_INVALIDCOLLATIONVALUE | 690 |
PE_ERR_STARTPAGEGREATERSTOPPAGE | 691 |
PE_ERR_READONLYPARAMETEROPTION | 700 |
PE_ERR_MINGREATERTHANMAX | 701 |
PE_ERR_INVALIDSTARTPAGE | 702 |
PE_ERR_OTHERERROR | 997 |
PE_ERR_INTERNALERROR | 998 | Programming error
PE_ERR_NOTIMPLEMENTED | 999 |


Event Id Constants

Constant | Description
PE_CLOSE_PRINT_WINDOW_EVENT |
PE_ACTIVATE_PRINT_WINDOW_EVENT |
PE_DEACTIVATE_PRINT_WINDOW_EVENT |
PE_PRINT_BUTTON_CLICKED_EVENT |
PE_EXPORT_BUTTON_CLICKED_EVENT |
PE_ZOOM_LEVEL_CHANGING_EVENT |
PE_FIRST_PAGE_BUTTON_CLICKED_EVENT |
PE_PREVIOUS_PAGE_BUTTON_CLICKED_EVENT |
PE_NEXT_PAGE_BUTTON_CLICKED_EVENT |
PE_LAST_PAGE_BUTTON_CLICKED_EVENT |
PE_CANCEL_BUTTON_CLICKED_EVENT |
PE_CLOSE_BUTTON_CLICKED_EVENT |
PE_SEARCH_BUTTON_CLICKED_EVENT |
PE_GROUP_TREE_BUTTON_CLICKED_EVENT |
PE_PRINT_SETUP_BUTTON_CLICKED_EVENT |
PE_REFRESH_BUTTON_CLICKED_EVENT |
PE_SHOW_GROUP_EVENT |
PE_DRILL_ON_GROUP_EVENT | Include drill on graph.
PE_DRILL_ON_DETAIL_EVENT |
PE_READING_RECORDS_EVENT |
PE_START_EVENT |
PE_STOP_EVENT |
PE_MAPPING_FIELD_EVENT |
PE_RIGHT_CLICK_EVENT | Right mouse click.
PE_LEFT_CLICK_EVENT | Left mouse click.
PE_MIDDLE_CLICK_EVENT | Middle mouse click.
PE_DRILL_ON_HYPERLINK_EVENT |
PE_LAUNCH_SEAGATE_ANALYSIS_EVENT |


Field Mapping Type Constants

Constant | Description
PE_FM_AUTO_FLD_MAP | Automatic field name mapping.
PE_FM_CRPE_PROMPT_FLD_MAP | CRPE provides dialog box to map field manually.
PE_FM_EVENT_DEFINED_FLD_MAP | CRPE provides list of fields in the report and the new database. This constant is not available in global32.bas.

Formula Syntax Constants

Constant | Description
PE_FST_CRYSTAL | Default value. See Remarks below.
PE_FST_BASIC | See Remarks below.

Remarks

For Running Total Condition Formulas:

  • PE_FST_CRYSTAL is the syntax for the eval formula.
  • PE_FST_BASIC is the syntax for the reset formula.


Graph Subtype Constants

The following chart subtypes are supported.

Bar Charts

Line Charts

Area Charts

Pie Charts

Doughnut Charts

3D Riser Charts

3D Surface Charts

Scatter Charts

Radar Charts

Bubble Charts

Stock (High/Low/Close Type) Charts

Misc Chart Types


Bar Charts

Constant

PE_GST_SIDEBYSIDEBARCHART

PE_GST_STACKEDBARCHART

PE_GST_PERCENTBARCHART

PE_GST_FAKED3DSIDEBYSIDEBARCHART

PE_GST_FAKED3DSTACKEDBARCHART

PE_GST_FAKED3DPERCENTBARCHART


Line Charts

Constant

PE_GST_REGULARLINECHART

PE_GST_STACKEDLINECHART

PE_GST_PERCENTAGELINECHART

PE_GST_LINECHARTWITHMARKERS

PE_GST_STACKEDLINECHARTWITHMARKERS

PE_GST_PERCENTAGELINECHARTWITHMARKERS


Area Charts

Constant

PE_GST_ABSOLUTEAREACHART

PE_GST_STACKEDAREACHART

PE_GST_PERCENTAREACHART

PE_GST_FAKED3DABSOLUTEAREACHART

PE_GST_FAKED3DSTACKEDAREACHART

PE_GST_FAKED3DPERCENTAREACHART


Pie Charts

Constant

PE_GST_REGULARPIECHART

PE_GST_FAKED3DREGULARPIECHART

PE_GST_MULTIPLEPIECHART

PE_GST_MULTIPLEPROPORTIONALPIECHART


Doughnut Charts

Constant

PE_GST_REGULARDOUGHNUTCHART

PE_GST_MULTIPLEDOUGHNUTCHART

PE_GST_MULTIPLEPROPORTIONALDOUGHNUTCHART


3D Riser Charts

Constant

PE_GST_THREEDREGULARCHART

PE_GST_THREEDPYRAMIDCHART

PE_GST_THREEDOCTAGONCHART

PE_GST_THREEDCUTCORNERSCHART


3D Surface Charts

Constant

PE_GST_THREEDSURFACEREGULARCHART

PE_GST_THREEDSURFACEWITHSIDESCHART

PE_GST_THREEDSURFACEHONEYCOMBCHART


Scatter Charts

Constant

PE_GST_XYSCATTERCHART

PE_GST_XYSCATTERDUALAXISCHART

PE_GST_XYSCATTERWITHLABELSCHART

PE_GST_XYSCATTERDUALAXISWITHLABELSCHART


Radar Charts

Constant

PE_GST_REGULARRADARCHART

PE_GST_STACKEDRADARCHART

PE_GST_RADARDUALAXISCHART


Bubble Charts

Constant

PE_GST_REGULARBUBBLECHART

PE_GST_DUALAXISBUBBLECHART


Stock (High/Low/Close Type) Charts

Constant

PE_GST_HIGHLOWCHART

PE_GST_HIGHLOWOPENCLOSECHART


Misc Chart Types

Constant

PE_GST_UNKNOWNSUBTYPECHART


Graph Text Font Constants

Constant

PE_GTF_TITLEFONT

PE_GTF_SUBTITLEFONT

PE_GTF_FOOTNOTEFONT

PE_GTF_GROUPSTITLEFONT

PE_GTF_DATATITLEFONT

PE_GTF_LEGENDFONT

PE_GTF_GROUPLABELSFONT

PE_GTF_DATALABELSFONT


Graph Title Type Constants

Constant

PE_GTT_TITLE

PE_GTT_SUBTITLE

PE_GTT_FOOTNOTE

PE_GTT_SERIESTITLE

PE_GTT_GROUPSTITLE

PE_GTT_XAXISTITLE

PE_GTT_YAXISTITLE

PE_GTT_ZAXISTITLE


Graph Type Constants

Constant | Description
PE_GT_BARCHART |
PE_GT_LINECHART |
PE_GT_AREACHART |
PE_GT_PIECHART |
PE_GT_DOUGHNUTCHART |
PE_GT_THREEDRISERCHART |
PE_GT_THREEDSURFACECHART |
PE_GT_SCATTERCHART |
PE_GT_RADARCHART |
PE_GT_BUBBLECHART |
PE_GT_STOCKCHART |
PE_GT_USERDEFINEDCHART | Use for PEGetGraphTypeInfo only. Do not use for PESetGraphTypeInfo.
PE_GT_UNKNOWNTYPECHART | Use for PEGetGraphTypeInfo only. Do not use for PESetGraphTypeInfo.


Group Condition Constants

The following tables list the Group Condition masks and constants applicable to various field types.

Group Condition Masks and Type Constants

All field types except Date and Boolean

Date and DateTime Fields

DateTime and Time Fields

Boolean Fields


Group Condition Masks and Type Constants

Mask and Type Constants | Value
PE_GC_CONDITIONMASK | 0x00FF
PE_GC_TYPEMASK | 0x0F00
PE_GC_TYPEOTHER | 0x0000
PE_GC_TYPEDATE | 0x0200
PE_GC_TYPEBOOLEAN | 0x0400
PE_GC_TYPETIME | 0x0800


All field types except Date and Boolean

Constant | Description
PE_GC_ANYCHANGE | Triggers a grouping every time there is a change.


Date and DateTime Fields

Constant (Date Fields Only) | Description
PE_GC_DAILY | Triggers a grouping every time the date changes.
PE_GC_WEEKLY | Triggers a grouping every time the date changes from one week to the next. (A week runs from Sunday through Saturday).
PE_GC_BIWEEKLY | Triggers a grouping every time the date changes from one two-week period to the next. (A week runs from Sunday through Saturday).
PE_GC_SEMIMONTHLY | Triggers a grouping every time the date changes from one half-month period to the next.
PE_GC_MONTHLY | Triggers a grouping every time the date changes from one month to the next.
PE_GC_QUARTERLY | Triggers a grouping every time the date changes from one calendar quarter to the next.
PE_GC_SEMIANNUALLY | Triggers a grouping every time the date changes from one half-year period to the next.
PE_GC_ANNUALLY | Triggers a grouping every time the date changes from one year to the next.


DateTime and Time Fields

Constant

PE_GC_BYSECOND

PE_GC_BYMINUTE

PE_GC_BYHOUR

PE_GC_BYAMPM


Boolean Fields

Constant (Boolean Fields Only) | Description
PE_GC_TOYES | Triggers a grouping every time the sort- and group-by field value changes from No to Yes.
PE_GC_TONO | Triggers a grouping every time the sort- and group-by field value changes from Yes to No.
PE_GC_EVERYYES | Triggers a grouping every time the sort- and group-by field value is Yes.
PE_GC_EVERYNO | Triggers a grouping every time the sort- and group-by field value is No.
PE_GC_NEXTISYES | Triggers a grouping every time the next value in the sort- and group-by field is Yes.
PE_GC_NEXTISNO | Triggers a grouping every time the next value in the sort- and group-by field is No.


Job Destination Constants

Constant | Description
PE_TO_NOWHERE | No destination.
PE_TO_WINDOW | Print to window.
PE_TO_PRINTER | Print to printer.
PE_TO_EXPORT | Export.
PE_FROM_QUERY | From a query.


Job Status Constants

Constant | Description
PE_JOBNOTSTARTED |
PE_JOBINPROGRESS |
PE_JOBCOMPLETED |
PE_JOBFAILED | An error occurred.
PE_JOBCANCELLED | The job was canceled by user.
PE_JOBHALTED | The job was halted because of too many records or too much time.


Object Type Constants

Constant

PE_OI_FIELDOBJECT

PE_OI_TEXTOBJECT

PE_OI_LINEOBJECT

PE_OI_BOXOBJECT

PE_OI_SUBREPORTOBJECT

PE_OI_OLEOBJECT

PE_OI_GRAPHOBJECT

PE_OI_CROSSTABOBJECT

PE_OI_BLOBFIELDOBJECT

PE_OI_MAPOBJECT

PE_OI_OLAPGRIDOBJECT


Ole Object Type Constants

Constant

PE_OOI_LINKEDOBJECT

PE_OOI_EMBEDDEDOBJECT

PE_OOI_STATICOBJECT


Ole Object Update Constants

Constant

PE_OOI_AUTOUPDATE

PE_OOI_MANUALUPDATE


Parameter Field Value Type Constants

Constant

PE_PF_NUMBER

PE_PF_CURRENCY

PE_PF_BOOLEAN

PE_PF_DATE

PE_PF_STRING

PE_PF_DATETIME

PE_PF_TIME


Range Info Constants

Constant | Value
PE_RI_INCLUDEUPPERBOUND | 1
PE_RI_INCLUDELOWERBOUND | 2
PE_RI_NOUPPERBOUND | 4
PE_RI_NOLOWERBOUND | 8


Section Codes

Constant

PE_ALLSECTIONS

PE_SECT_PAGE_HEADER

PE_SECT_PAGE_FOOTER

PE_SECT_REPORT_HEADER

PE_SECT_REPORT_FOOTER

PE_SECT_GROUP_HEADER

PE_SECT_GROUP_FOOTER

PE_SECT_DETAIL


Sort Method Constants

Constant

PE_OR_NO_SORT

PE_OR_ALPHANUMERIC_ASCENDING

PE_OR_ALPHANUMERIC_DESCENDING

PE_OR_NUMERIC_ASCENDING

PE_OR_NUMERIC_DESCENDING


Sort Order Constants

Constant | Description
PE_SF_DESCENDING | Sorts data in descending order (Z to A, 9 to 1).
PE_SF_ASCENDING | Sorts data in ascending order (A to Z, 1 to 9).
PE_SF_ORIGINAL | Group condition only: Sorts data in its original order.
PE_SF_SPECIFIED | Group condition only: Sorts data in a specified order. Read only.


Track Cursor Constants

Constant | Description
PE_TC_DEFAULT_CURSOR | CRPE default cursor = PE_TC_ARROW_CURSOR.
PE_TC_ARROW_CURSOR | Arrow cursor.
PE_TC_CROSS_CURSOR | Cross cursor.
PE_TC_IBEAM_CURSOR | I-beam cursor.
PE_TC_UPARROW_CURSOR | Arrow cursor pointing to the top of the screen.
PE_TC_SIZEALL_CURSOR | 32-bit only.
PE_TC_SIZENWSE_CURSOR | Sizing cursor when resizing from the top, left-hand side of the screen to the bottom, right-hand side of the screen.
PE_TC_SIZENESW_CURSOR | Sizing cursor when resizing from the top, right-hand side of the screen to the bottom, left-hand side of the screen.
PE_TC_SIZEWE_CURSOR | Sizing cursor when resizing from the left side of the screen to the right side of the screen.
PE_TC_SIZENS_CURSOR | Sizing cursor when resizing from the top of the screen to the bottom of the screen.
PE_TC_NO_CURSOR | 32-bit only.
PE_TC_WAIT_CURSOR | Wait (i.e., hourglass) cursor.
PE_TC_APPSTARTING_CURSOR | 32-bit only.
PE_TC_HELP_CURSOR | 32-bit only.
PE_TC_SIZE_CURSOR | Not used in 32-bit applications. Use PE_TC_SIZEALL_CURSOR.
PE_TC_ICON_CURSOR | Not used in 32-bit applications. Use PE_TC_ARROW_CURSOR.
PE_TC_BACKGROUND_PROCESS_CURSOR | CRPE specific cursor.
PE_TC_GRAB_HAND_CURSOR | CRPE specific cursor.
PE_TC_ZOOM_IN_CURSOR | CRPE specific cursor.
PE_TC_REPORT_SECTION_CURSOR | CRPE specific cursor.
PE_TC_HAND_CURSOR | CRPE specific cursor.
PE_TC_MAGNIFY_CURSOR | CRPE specific cursor. Magnifying glass cursor (used for drill-down).


Zoom Level Constants

Constant

PE_ZOOM_FULL_SIZE

PE_ZOOM_SIZE_FIT_ONE_SIDE

PE_ZOOM_SIZE_FIT_BOTH_SIDES


Obsolete Functions, Structures, and Constants

The following obsolete functions, structures, and constants are listed alphabetically. They are not supported by the current version. Where appropriate, replacement or updated equivalents are listed. The corresponding new call should be used in all new applications.


Obsolete Functions

Obsolete Function | Replacement Function
PEGetGraphData |
PEGetGraphOptions | PEGetGraphOptionInfo
PEGetGraphText | PEGetGraphTextInfo
PEGetGraphType | PEGetGraphTypeInfo
PEGetMinimumSectionHeight | PEGetSectionHeight
PEGetNParams | PEGetNParameterFields
PEGetNthParam | PEGetNthParameterField
PEGetNthParamInfo | PEGetParameterValueInfo
PESetGraphData |
PESetGraphOptions | PESetGroupOptions
PESetGraphText | PESetGraphTextInfo
PESetGraphType | PESetGraphTypeInfo
PESetMinimumSectionHeight | PESetSectionHeight
PESetNthParam | PESetNthParameterField


Obsolete Structures

Obsolete Structure

PECharSepFileOptions

PEGraphDataInfo

PEGraphOptions

PEGraphTextInfo

PEParameterInfo

PEPrintFileOptions


Obsolete Constants

Obsolete Constants

PE_GRAPH_XXX Graph Direction Constants

PE_SIDE_ / PE_FAKED_ /etc. Graph Type Constants


The Crystal Report Engine Class Library Reference

The Crystal Report Engine Class Library is based on the Microsoft Foundations Class Library, and provides an object oriented approach to programming the Crystal Report Engine in C++. In this section you will find detailed information on methods, structures and constants, along with a list of obsolete methods and structures.

Click the appropriate link to jump to that section:

  • The Crystal Report Engine Class Library
  • class CRPEngine
  • class CRPEJob
  • class CRPEJob : public CObject
  • class CRPEJob Methods
  • class CRPEngine and class CRPEJob Constants
  • class CRPEngine and class CRPEJob Obsolete Methods


The Crystal Report Engine Class Library

Introduction

The Crystal Report Engine Class (REC) Library provides object oriented programming of the Crystal Report Engine in C++. The Crystal REC Library is based on the Microsoft Foundation Class (MFC) Library. The two Crystal Report Engine Class definitions in the Crystal REC Library are derived from the MFC CObject class.

MFC is a widely available, and highly powerful class library originally designed for use with Microsoft's C++ development environment (Microsoft Visual C++). However, MFC is a complete class library designed for programming Windows applications and can be used with most C++ development environments.

The Crystal REC Library is comprised of two primary classes and several supporting structures. These classes are wrapped around the Crystal Report Engine API, providing an object oriented approach to programming the Crystal Report Engine.

Note: The Crystal REC Library can be used with any available version of the MFC Library.

The Crystal REC Library was installed in the same directory as Crystal Report (\CRW by default). You need to add the following files to your C++ project to use the Crystal REC Library:

  • PEPLUS.H

This C++ header file contains the Crystal Report Engine class definitions along with several structure definitions used by the Crystal Report Engine classes. You must #include PEPLUS.H in any code module that will be using the Crystal Report Engine classes.

  • PEPLUS.CPP

This C++ source code file contains implementations of all of the class methods for the Crystal REC Library classes. PEPLUS.CPP must be added to your C++ project file in order to use the Crystal REC Library. This code is compiled directly into your Visual C++ project and calls the functions available in the Crystal Report Engine.

  • CRPE32M.LIB

As mentioned above, the Crystal REC Library classes are wrapped around the Crystal Report Engine API, and the methods in these classes make direct calls to the functions in the Crystal Report Engine API. For this reason, your project must include the CRPE32M.LIB Crystal Report Engine library. Make sure CRPE32M.LIB has been added to the list of libraries included with your C++ project.


Classes in the Crystal Report Engine Class Library

The Crystal REC Library consists of two primary classes:

  • The class CRPEngine, controls the entire Crystal Report Engine. It is designed so that there should only be one CRPEngine object in the entire application. The CRPEngine object contains methods that are common to all print jobs (i.e., SQL connections, version information, etc.). More importantly, it is responsible for creating and managing all CRPEJob objects.
  • The class CRPEJob, controls print jobs. A print job is a request for a report to be processed and printed, previewed, or exported. You do not construct a CRPEJob object directly; instead, you request a job instance from the CRPEngine class and receive a pointer to a CRPEJob object. It is the CRPEJob object that allows you access to the attributes of a print job.

Both classes are derived from the MFC CObject class and provide all of the functionality of that class, including runtime class information and object diagnostic output.


class CRPEngine

This section describes the class CRPEngine:publicCObject and methods.

class CRPEngine : public CObject

The CRPEngine class is designed so that there should be only one CRPEngine object in the entire application. The CRPEngine object contains methods that are common to all print jobs (SQL connections, version information, etc.). More importantly, CRPEngine is responsible for creating and managing all CRPEJob objects. It is the CRPEJob object that allows you access to the attributes of a print job.

In order to open a particular report, it is first necessary to have an open Crystal Report Engine object in the application. You may then call the CRPEngine::OpenPrintJob member function specifying the report file name that you want to open. If successful, you will be returned a pointer to a CRPEJob object.

Constructor CRPEngine::CRPEngine

CRPEngine::CRPEngine is the constructor for the class. If the open parameter is true, the actual Crystal Reports DLL is opened (crpe32.dll). Print jobs may only be opened if the engine itself is open. If originally opened with open = FALSE, the engine may be opened later with CRPEngine::Open.

Constructor Syntax
CRPEngine ( BOOL open );
Parameter

open

Indicates whether the Crystal Report Engine should be opened when the CRPEngine object is created. The default for this parameter is FALSE.


class CRPEngine Methods

The following methods are discussed in this section.

CRPEngine::AddJob

CRPEngine::CanClose

CRPEngine::Close

CRPEngine::GetErrorCode

CRPEngine::GetErrorText

CRPEngine::GetHandleString

CRPEngine::GetNPrintJobs

CRPEngine::GetVersion

CRPEngine::LogOffServer

CRPEngine::LogOnServer

CRPEngine::LogOnSQLServerWithPrivateInfo

CRPEngine::Open

CRPEngine::OpenJob

CRPEngine::PrintReport

CRPEngine::RemoveJob


CRPEngine::AddJob

Use CRPEngine::AddJob to add a new job object.

Syntax

void AddJob ( CRPEJob *job );

Parameter

job

Specifies a pointer to the CRPEJob object.


CRPEngine::CanClose

Use CRPEngine::CanClose to determine whether the Crystal Report Engine is busy. Errors can occur in your application or on a system if you attempt to close the Crystal Report Engine while it is processing a print job. To determine whether the Report Engine can be closed safely in an application, use this method before attempting to close the Crystal Report Engine (for example, when the user tries to exit).

Syntax

BOOL CanClose ();

Returns
  • TRUE if the Crystal Report Engine can be closed.
  • FALSE if Crystal Report Engine is still busy.


CRPEngine::Close

Use CRPEngine::Close to close the Crystal Report Engine.

Syntax
void Close ();


CRPEngine::GetEngine

Use CRPEngine::GetEngine to retrieve a pointer to the current CRPEngine object being used in the application.

Syntax

static CRPEngine *GetEngine ();

Returns

Returns a pointer to the current CRPEngine object.


CRPEngine::GetEngineStatus

Use CRPEngine::GetEngineStatus to get the current engine status.

Syntax

static Status GetEngineStatus ();

Returns

Returns one of the following values of Status enumerated type indicating the current status of the Crystal Report Engine.
engineOpen | The Crystal Report Engine is currently open.
engineClosed | The Crystal Report Engine is not yet open, or has been closed.
engineMissing | No Crystal Report Engine is available. Make sure the Crystal Report Engine DLL is located in a directory that appears in your PATH.


CRPEngine::GetErrorCode

Use CRPEngine::GetErrorCode to retrieve the current error code of the Crystal Report Engine. When a call to another function fails, this call retrieves the error code that was generated so that you can take some action based on that error code.

Syntax

short GetErrorCode ();

Returns
  • Returns the current Crystal Report Engine Error Codes.
  • Returns 0 (zero) if no error has occurred.


CRPEngine::GetErrorText

Use CRPEngine::GetErrorText to retrieve a descriptive Crystal Report Engine error message.

Syntax

CString GetErrorText ();

Returns

Returns a CString object containing the text for the current error.


CRPEngine::GetHandleString

Use CRPEngine::GetHandleString to retrieve the text to which the string handle is pointing. The CString object will contain the actual text. This function is used in conjunction with functions that return variable length strings. After your program allocates a buffer of sufficient size, this function moves the string from the string handle to the buffer.

BOOL GetHandleString (

        HANDLE textHandle,

        short textLength,

        CString &string );
Parameters
textHandle | Specifies the handle of the string containing the text of interest.
textLength | Specifies the length of the text string, including the terminating null byte. This value should be identical to the length of the string obtained by the variable length string function.
string | Reference to the CString object obtained by the variable length string function.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Because the string handle is discarded once the method is called, you can use this call only once with a given string handle. If you expect to use the string later, you will need to save it.
  • When you call the method that produces the string, it returns a length that includes a provision for the null byte at the end of the string. A buffer set to that length will hold the entire string, including the terminating null byte.


CRPEngine::GetNPrintJobs

Use CRPEngine::GetNPrintJobs to retrieve the number of print job (CRPEJob) objects that currently exist for the current CRPEngine object.

Syntax

int GetNPrintJobs ();

Returns
  • Returns the number of CRPEJob objects currently open.
  • Returns -1 if an error occurs.


CRPEngine::GetVersion

Use CRPEngine::GetVersion to retrieve the version number of the Crystal Report Engine DLL (CRPE32.DLL) or the version number of the Crystal Report Engine itself. The high-order byte is the major version number and the low-order byte is the minor version number.

This method can be used whenever you build functionality into a report that may not be available in earlier versions of the Crystal Report Engine and you need to verify the version number first. This function can be a safeguard for users who have more than one version of the Crystal Report Engine with the older version appearing earlier in the path than the newer version.

Syntax

short GetVersion ( short versionRequested );

Parameters

versionRequested | Specifies whether the version number of the Crystal Report Engine or the Crystal Report Engine DLL is being requested. Use one of the following constants.
 | Constant | Description
 | PEP_GV_DLL | Returns the version of the DLL.
 | PEP_GV_ENGINE | Returns the version of the Crystal Report Engine.

Returns

Returns the version number of the currently used Crystal Report Engine or Crystal Report Engine DLL.


CRPEngine::LogOffServer

Use CRPEngine::LogOffServer to close an existing connection to an SQL server. Connection information is provided through CRPELogOnInfo.

Syntax
BOOL LogOffServer (

        const _TCHAR *dllName,

        const CRPELogOnInfo *logOnInfo );
Parameters
dllName | Specifies a pointer to the name of the Crystal Reports DLL for the server or password protected non-SQL table from which you want to log off.
logOnInfo | Specifies a pointer to CRPELogOnInfo.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEngine::LogOnServer

Use CRPEngine::LogOnServer to open a connection to an SQL server. More than one print job may use this connection to the SQL server. Information required to establish a connection is provided through CRPELogOnInfo.

Syntax
BOOL LogOnServer (

        const _TCHAR *dllName,

        const CRPELogOnInfo *logOnInfo );
Parameters
dllName | Specifies a pointer to the name of the Crystal Reports DLL for the server or password-protected non-SQL table to which you want to log on.
logOnInfo | Specifies a pointer to CRPELogOnInfo.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEngine::LogOnSQLServerWithPrivateInfo

Use CRPEngine::LogOnSQLServerWithPrivateInfo to allow the Crystal Report Engine to "piggyback" your application's existing connection to a Server. This lowers the number of connections established by a workstation, reducing application time and network traffic. It also prevents a Crystal Reports LogOff call from disconnecting an application's existing connection to the Server.

Syntax
BOOL LogOnSQLServerWithPrivateInfo (

        const _TCHAR *dllName,

        void *privateInfo );
Parameters
dllName | Specifies the name of the DLL that was used when establishing a connection to the Server (when the report was first created). For example, if a report was created using an ODBC data source, specify the filename "PDSODBC.DLL". For more information on possible database DLLs, refer to Crystal Reports Developer Runtime Help (Runtime.hlp).
privateInfo | Specifies a pointer to the application's handle to the Server connection. In your application, a connection to the Server must already be established before this method is called. Pass the HDBC (handle to a database connection) from this connection to the privateInfo parameter.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • This method can be used only with database connections established by ODBC or Q+E Library 2.0. Any other database connections cannot be accessed by this method.
  • To obtain an HDBC for an ODBC connection, use the following function calls (see the ODBC SDK 2.0 manual for more information).
    Call Description

    SQLAllocEnv

    Initializes the ODBC call level interface and allocates memory for an environment handle.

    SQLAllocConnect

    Returns an ODBC HDBC.

  • To obtain an HDBC for a Q+E Library connection, use the following function calls (see the InterSolv DataDirect Developer's Toolkit for more information).
    Call Description

    qeConnect

    Opens a connection to the server.

    qeGetODBCHdbc

    Returns the ODBC HDBC.


CRPEngine::Open

Use CRPEngine::Open to open the Crystal Report Engine. This method is necessary only if you constructed the CRPEngine object with the open parameter equal to FALSE. If you set the open parameter to TRUE when you constructed the CRPEngine object, this method is unnecessary.

Syntax

BOOL Open ();

Returns
  • TRUE if the Crystal Report Engine was opened successfully.
  • FALSE if the call failed.


CRPEngine::OpenJob

Use CRPEngine::OpenJob to open the report specified by reportFileName. A pointer to a CRPEJob object is returned. Print job attributes may be referenced through this object.

Syntax

CRPEJob *OpenJob ( const _TCHAR *reportFileName );

Parameter

reportFileName

Specifies a pointer to the name and path (if necessary) of the report file being opened for the specified print job.

Returns

Returns a pointer to a CRPEJob object for the opened print job.


CRPEngine::PrintReport

Use CRPEngine::PrintReport to provide a quick but limited way to print a report. The report may be sent only to a printer or preview window or both. Use this class method any time that you simply want to print a report from an application without giving the user the ability to customize the report.

Syntax
short PrintReport (

        const _TCHAR *reportFilePath,

        BOOL toPrinter,

        BOOL toWindow,

        const _TCHAR *title,

        int left,

        int top,

        int width,

        int height,

        DWORD style,

        CWnd *parentWindow );
Parameters
reportFilePath | Specifies a pointer to the filename and path of the report to be printed.
toPrinter | Specifies whether the report is to be sent to the default printer.
toWindow | Specifies whether the report is to be displayed in a preview window.
title | Specifies a pointer to the title string that you want to appear in the title bar (if the report is being sent to a preview window).
left | Specifies the x coordinate of the upper left-hand corner of the preview window, in device coordinates.
top | Specifies the y coordinate of the upper left-hand corner of the preview window, in device coordinates.
width | Specifies the width of the preview window, in device coordinates.
height | Specifies the height of the preview window, in device coordinates.
style | Specifies the style of the window being created. The style setting can be combined using the bitwise "OR" operator. Refer to the CWnd class in the Microsoft Foundation Class Library reference for possible window styles.
parentWindow | Specifies a pointer to the CWnd object for the window that is the parent of the preview window. Specify NULL if the preview window will not have a parent window.
Returns
  • Returns 0 (zero) if the call is successful.
  • Returns an error code if an error occurs.


CRPEngine::RemoveJob

Use CRPEngine::RemoveJob to remove a job object.

Syntax

void RemoveJob ( CRPEJob *job );

Parameter

job

Specifies a pointer to the CRPEJob object that you want to remove.


class CRPEJob

This section describes the class CRPEJob public CObject and methods.


class CRPEJob : public CObject

In order to open a particular report, it is first necessary to have an open Crystal Report Engine object in the application. You may then call the member function CRPEngine::OpenJob, specifying the report file name to open. If successful, you will be returned a pointer to the CRPEJob object. It is through this object that you may modify the print job attributes as well as output the report in various formats. Almost all these methods correspond to similar functions available in the Crystal Report Engine API.

Constructor CRPEJob::CRPEJob

  • This class constructor is called automatically by CRPEngine::OpenJob. Do not call this constructor from within your own code.
  • This class constructor also stores the job number internally for future use in Crystal Report Engine API calls.
Constructor Syntax
CRPEJob ( short jobHandle );
CRPEJob (  short jobHandle,

        CRPEJob *parentJob );


class CRPEJob Methods

The following methods are discussed in this section, arranged alphabetically.

class CRPEJob Methods A...F

class CRPEJob Methods G (Get...)

class CRPEJob Methods H...Z


class CRPEJob Methods A...F

CRPEJob::AddParameterCurrentRange

CRPEJob::AddParameterCurrentValue

CRPEJob::AddParameterDefaultValue

CRPEJob::Cancel

CRPEJob::CheckFormula

CRPEJob::CheckGroupSelectionFormula

CRPEJob::CheckNthTableDifferences

CRPEJob::CheckSelectionFormula

CRPEJob::CheckSQLExpression

CRPEJob::ClearParameterCurrentValuesAndRanges

CRPEJob::Close

CRPEJob::CloseSubreport

CRPEJob::CloseWindow

CRPEJob::ConvertPFInfoToVIInfo

CRPEJob::ConvertVIInfoToPFInfo

CRPEJob::DeleteNthGroupSortField

CRPEJob::DeleteNthParameterDefaultValue

CRPEJob::DeleteNthSortField

CRPEJob::DiscardSavedData

CRPEJob::EnableEvent

CRPEJob::EnableProgressDialog

CRPEJob::ExportPrintWindow

CRPEJob::ExportTo

CRPEJob::FreeDevMode

class CRPEJob Methods G (Get...)

CRPEJob::GetAllowPromptDialog

CRPEJob::GetAreaFormat

CRPEJob::GetAreaFormatFormula

CRPEJob::GetEnableEventInfo

CRPEJob::GetErrorCode

CRPEJob::GetErrorText

CRPEJob::GetExportOptions

CRPEJob::GetFieldMappingType

CRPEJob::GetFormula

CRPEJob::GetFormulaSyntax

CRPEJob::GetGraphAxisInfo

CRPEJob::GetGraphFontInfo

CRPEJob::GetGraphOptionInfo

CRPEJob::GetGraphTextDefaultOption

CRPEJob::GetGraphTextInfo

CRPEJob::GetGraphTypeInfo

CRPEJob::GetGroupCondition

CRPEJob::GetGroupOptions

CRPEJob::GetGroupSelectionFormula

CRPEJob::GetJobHandle

CRPEJob::GetJobStatus

CRPEJob::GetMargins

CRPEJob::GetNDetailCopies

CRPEJob::GetNFormulas

CRPEJob::GetNGroups

CRPEJob::GetNGroupSortFields

CRPEJob::GetNPages

CRPEJob::GetNParameterCurrentRanges

CRPEJob::GetNParameterCurrentValues

CRPEJob::GetNParameterDefaultValues

CRPEJob::GetNParameterFields

CRPEJob::GetNSections

CRPEJob::GetNSectionsInArea

CRPEJob::GetNSortFields

CRPEJob::GetNSQLExpressions

CRPEJob::GetNSubreportsInSection

CRPEJob::GetNTables

CRPEJob::GetNthFormula

CRPEJob::GetNthGroupSortField

CRPEJob::GetNthParameterCurrentRange

CRPEJob::GetNthParameterCurrentValue

CRPEJob::GetNthParameterDefaultValue

CRPEJob::GetNthParameterField

CRPEJob::GetNthParameterType

CRPEJob::GetNthParameterValue Description

CRPEJob::GetNthSortField

CRPEJob::GetNthSQLExpression

CRPEJob::GetNthSubreportInSection

CRPEJob::GetNthTableLocation

CRPEJob::GetNthTableLogOnInfo

CRPEJob::GetNthTablePrivateInfo

CRPEJob::GetNthTableSessionInfo

CRPEJob::GetNthTableType

CRPEJob::GetParameterMinMaxValue

CRPEJob::GetParameterPickListOption

CRPEJob::GetParameterValueInfo

CRPEJob::GetPrintDate

CRPEJob::GetPrintOptions

CRPEJob::GetReportOptions

CRPEJob::GetReportSummaryInfo

CRPEJob::GetReportTitle

CRPEJob::GetSectionCode

CRPEJob::GetSectionFormat

CRPEJob::GetSectionFormatFormula

CRPEJob::GetSectionHeight

CRPEJob::GetSelectedPrinter

CRPEJob::GetSelectionFormula

CRPEJob::GetSQLExpression

CRPEJob::GetSQLQuery

CRPEJob::GetSubreportInfo

CRPEJob::GetTrackCursorInfo

CRPEJob::GetWindowHandle

CRPEJob::GetWindowOptions

class CRPEJob Methods H...Z

CRPEJob::HasSavedData

CRPEJob::IsJobFinished

CRPEJob::NextWindowMagnification

CRPEJob::OpenSubreportJob

CRPEJob::OutputToPrinter

CRPEJob::OutputToWindow

CRPEJob::PrintControlsShowing

CRPEJob::PrintWindow

CRPEJob::ReimportSubreport

CRPEJob::SelectPrinter

CRPEJob::SetAllowPromptDialog

CRPEJob::SetAreaFormat

CRPEJob::SetAreaFormatFormula

CRPEJob::SetDialogParentWindow

CRPEJob::SetEventCallback

CRPEJob::SetFieldMappingType

CRPEJob::SetFont

CRPEJob::SetFormula

CRPEJob::SetFormulaSyntax

CRPEJob::SetGraphAxisInfo

CRPEJob::SetGraphFontInfo

CRPEJob::SetGraphOptionInfo

CRPEJob::SetGraphTextDefaultOption

CRPEJob::SetGraphTextInfo

CRPEJob::SetGraphTypeInfo

CRPEJob::SetGroupCondition

CRPEJob::SetGroupOptions

CRPEJob::SetGroupSelectionFormula

CRPEJob::SetMargins

CRPEJob::SetNDetailCopies

CRPEJob::SetNthGroupSortField

CRPEJob::SetNthParameterDefaultValue

CRPEJob::SetNthParameterField

CRPEJob::SetNthParameterValueDescription

CRPEJob::SetNthSortField

CRPEJob::SetNthTableLocation

CRPEJob::SetNthTableLogOnInfo

CRPEJob::SetNthTablePrivateInfo

CRPEJob::SetNthTableSessionInfo

CRPEJob::SetParameterMinMaxValue

CRPEJob::SetParameterPickListOption

CRPEJob ::SetParameterValueInfo

CRPEJob::SetPrintDate

CRPEJob::SetPrintOptions

CRPEJob::SetReportOptions

CRPEJob::SetReportSummaryInfo

CRPEJob::SetReportTitle

CRPEJob::SetSectionFormat

CRPEJob::SetSectionFormatFormula

CRPEJob::SetSectionHeight

CRPEJob::SetSelectionFormula

CRPEJob::SetSQLExpression

CRPEJob::SetSQLQuery

CRPEJob::SetTrackCursorInfo

CRPEJob::SetWindowOptions

CRPEJob::Show...Page

CRPEJob::ShowPrintControls

CRPEJob::Start

CRPEJob::SVA2T

CRPEJob::SVT2A

CRPEJob::TestNthTableConnectivity

CRPEJob::VerifyDatabase

CRPEJob::ZoomPreviewWindow


CRPEJob::AddParameterCurrentRange

Use CRPEJob::AddParameterCurrentRange to add a parameter range to the specified parameter field of a report.

Syntax
BOOL AddParameterCurrentRange (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        CRPEValueInfo *rangeStart,

        CRPEValueInfo *rangeEnd,

        short rangeInfo );
Parameters

parameterField Name | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.
rangeStart | Specifies a pointer to CRPEValueInfo, which will contain the new lower bound of the value range.
rangeEnd | Specifies a pointer to CRPEValueInfo, which will contain the new upper bound of the value range.
rangeInfo | Use this bit mapped value to indicate whether the upper and/or lower bound of the range should be included. Set rangeInfo to one of the following constants.
 | Constant | Value | Description
 | PEP_RI_NOUPPERBOUND | 4 | rangeStart must contain valid information. Set rangeEnd to NULL.
 | PEP_RI_NOLOWERBOUND | 8 | rangeEnd must contain valid information. Set rangeStart to NULL.
 | PEP_RI_INCLUDEUPPERBOUND OR PEP_RI_INCLUDELOWERBOUND | 3 | Both rangeStart and rangeEnd must contain valid information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Set rangeStart to NULL to retrieve maximum value only. rangeStart must be non-NULL if rangeEnd is NULL.
  • Set rangeEnd to NULL to retrieve minimum value only. rangeEnd must be non-NULL if rangeStart is NULL.
  • If both rangeStart and rangeEnd are specified (that is, non-NULL), then the valueType member of CRPEValueInfo for rangeStart and rangeEnd must be the same or an error code PEP_ERR_INCONSISTANTTYPES will be returned.


CRPEJob::AddParameterCurrentValue

Use CRPEJob::AddParameterCurrentValue to add a current value to the specified parameter field in the specified report.

Syntax
BOOL AddParameterCurrentValue (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        CRPEValueInfo *currentValue );
Parameters
parameterFieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.
currentValue | Specifies a pointer to the CRPEValueInfo, which will contain the current value to be added to the parameter field.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::AddParameterDefaultValue

Use CRPEJob::AddParameterDefaultValue to add a default value to a specified parameter field in a specified report.

Syntax
BOOL AddParameterDefaultValue (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        CRPEValueInfo *valueInfo );
Parameters
parameterFieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.
valueInfo | Specifies a pointer to CRPEValueInfo, which will contain the default value to be added to the parameter field.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::Cancel

Use CRPEJob::Cancel to cancel processing of a print job. This method can be tied to a control that allows the user to cancel a print job in progress.

Syntax

void Cancel ();

CRPEJob::CheckFormula

Use CRPEJob::CheckFormula to check a formula for validity. This method works just like the Check button in Crystal Reports Formula Editor. If the named formula contains an error, the method returns FALSE.

Syntax

BOOL CheckFormula ( const _TCHAR *formulaName );

Parameter

formulaName

Specifies a pointer to the name of the formula that you want to check for errors.

Returns
  • TRUE if the formula text is correct.
  • FALSE if the checked formula contains an error or if the call fails.


CRPEJob::CheckGroupSelectionFormula

Use CRPEJob::CheckGroupSelectionFormula to check the group selection formula for the report for errors. This method works just like the Check button in Crystal Reports Formula Editor. If the group selection formula contains an error, the method returns FALSE.

Syntax

BOOL CheckGroupSelectionFormula ();

Returns
  • TRUE if the formula text is correct.
  • FALSE if the checked formula contains an error or if the call fails.


CRPEJob::CheckNthTableDifferences

Use CRPEJob::CheckNthTableDifferences to retrieve information about table differences.

Syntax
BOOL CheckNthTableDifferences (

        short tableN,

        CRPETableDifferenceInfo *tableDifferenceInfo );
Parameters
tableN | Specifies the 0-based number of the table for which you want to retrieve change information.
tableDifferenceInfo | Specifies a pointer to CRPETableDifferenceInfo, which will contain the information retrieved.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::CheckSelectionFormula

Use CRPEJob::CheckSelectionFormula to check the record selection formula for the report for errors. This method works just like the Check button in Crystal Reports Formula Editor. If the selection formula contains an error, the method returns FALSE.

Syntax

BOOL Check SelectionFormula ();

Returns
  • TRUE if the formula text is correct.
  • FALSE if the checked formula contains an error or if the call fails.


CRPEJob::CheckSQLExpression

Use CRPEJob::CheckSQLExpression to check the specified SQL expression for errors. If the SQL expression contains an error, the method returns FALSE.

Syntax

BOOL CheckSQLExpression ( const _TCHAR *expressionName );

Parameter

expressionName

Specifies a pointer to the name of the SQL expression that you want to check.

Returns
  • TRUE if the formula text is correct.
  • FALSE if the checked formula contains an error or if the call fails.


CRPEJob::ClearParameterCurrentValuesAndRanges

Use CRPEJob::ClearParameterCurrentValuesAndRanges to clear the specified parameter field of all current values and ranges.

Syntax
BOOL ClearParameterCurrentValuesAndRanges (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName );
Parameters
parameterFieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::CloseSubreport

Use CRPEJob::CloseSubreport to close a subreport.

Syntax

BOOL CloseSubreport ();

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::Close

Use CRPEJob::Close to close the print job and delete the CRPEJob object. This method calls the destructor for the CRPEJob object. Printing will continue if it has not completed when this method is called. If the preview window is open, it stays open.

Syntax

void Close ();


CRPEJob::CloseWindow

Use CRPEJob::CloseWindow to close the preview window. If you are customizing preview window controls, implement this method to allow the user to close the preview window when finished with viewing the report.

Syntax

void CloseWindow ();


CRPEJob::ConvertPFInfoToVIInfo

Use to CRPEJob::ConvertPFInfoToVIInfo convert parameter field info to value info.

Syntax
      BOOL ConvertPFInfoToVInfo (

        void FAR * value,

        short valueType,

        CRPEValueInfo *valueInfo );
Parameters
value | Specifies a pointer to the value to be converted.
valueType | Specifies the value type.
valueInfo | Specifies a pointer to CRPEValueInfo.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::ConvertVIInfoToPFInfo

Use to CRPEJob::ConvertVIInfoToPFInfo convert value info to parameter field info.

Syntax
     BOOL ConvertVInfoToPFInfo (

        CRPEValueInfo *valueInfo,

        WORD *valueType,

        void *value );
Parameters
valueInfo | Specifies a pointer to CRPEValueInfo.
valueType | Specifies a pointer to the value type.
value | Specifies a pointer to the value to be converted.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::DeleteNthGroupSortField

Use CRPEJob::DeleteNthGroupSortField to delete the group sort field at the specified position. The group and group summary are not removed from the report, but the field is removed from the list of group sort fields and the summary data appearing in the group field is no longer sorted.

Syntax

BOOL DeleteNthGroupSortField ( short sortFieldN );

Parameter

sortFieldN

Specifies the number of the group sort field that you want to delete. The first group sort field added to the report is field 0, the second is 1, etc.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::DeleteNthParameterDefaultValue

Use CRPEJob::DeleteNthParameterDefaultValue to remove the indicated default value from the specified parameter field in the specified report.

Syntax
BOOL DeleteNthParameterDefaultValue (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        short index );
Parameters
parameterFieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.
index | Specifies the index of the default value to remove.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::DeleteNthSortField

Use CRPEJob::DeleteNthSortField to remove the specified sort field from the report. The field is not deleted from the report but it is removed from the list of sort fields, and data in that field no longer appears sorted.

Syntax

BOOL DeleteNthSortField ( short sortFieldN );

Parameter

sortFieldN

Specifies the number of the sort field that you want to delete. The first sort field added to the report is field 0, the second is 1, etc.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::DiscardSavedData

Use CRPEJob::DiscardSavedData to discard data that was previously saved with the report. If a report has been saved with data, you can use this method to discard the saved data, forcing the Crystal Report Engine to retrieve new data when the report is printed.

Syntax

BOOL DiscardSavedData ();

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::EnableEvent

Use CRPEJob::EnableEvent to enable/disable the group event specified by CRPEEnableEventInfo. All events are disabled by default.

Syntax

BOOL EnableEvent ( const CRPEEnableEventInfo *enableEventInfo );

Parameter

enableEventInfo

Specifies a pointer to CRPEEnableEventInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::EnableProgressDialog

Use CRPEJob::EnableProgressDialog to enable/disable the display of the Progress dialog box. The Progress dialog box displays the progress of the report when it is running (records read, records selected, etc.).

Syntax

BOOL EnableProgressDialog ( BOOL enable );

Parameter

enable

Specifies whether the progress dialog box is enabled. If this parameter is set to TRUE, the progress dialog box is enabled; if set to FALSE, the dialog box is disabled.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::ExportPrintWindow

Use CRPEJob::ExportPrintWindow to export the report displayed in the preview window to a disk file or e-mail address. If you are customizing preview window controls, use this method to enable the user to preview the report in the preview window, and if everything looks satisfactory, to export the report to a disk file or e-mail address (in response to a user event, such as a button click, menu command, etc.).

Syntax

BOOL ExportPrintWindow ( BOOL toMail );

Parameter

toMail

Specifies whether the report file should be exported to an e-mail address. If TRUE, the file is exported to e-mail. If FALSE, the file is exported to a disk file.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::ExportTo

Use CRPEJob::ExportTo to set the output of the print job to be exported. The export format is specified through the options parameter. This method does not export the report, but specifies that when the report is printed, it will be exported to a disk file or e-mail address according to settings in the options parameter. To actually export the report, use CRPEJob::Start.

Syntax

BOOL ExportTo ( const CRPEExportOptions *options );

Parameter

options

Specifies a pointer to CRPEExportOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::FreeDevMode

Use CRPEJob::FreeDevMode to return the memory associated with the specified DEVMODE Microsoft Windows structure to the heap. The DEVMODE structure must have been retrieved from CRPEJob::SelectPrinter, or CRPEJob::GetSelectedPrinter.

Syntax

BOOL FreeDevMode ( DEVMODEA *mode );

Parameter

mode

Specifies a pointer to Microsoft Windows structure DEVMODE.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetAllowPromptDialog

Use CRPEJob::GetAllowPromptDialog to determine if prompting for parameter values is allowed during printing for this job.

Syntax

BOOL GetAllowPromptDialog ();

Returns

Returns a Boolean value indicating whether prompting for parameter values is allowed during printing of a job. TRUE indicates that prompting is allowed.


CRPEJob::GetAreaFormat

Use CRPEJob::GetAreaFormat to set format information for the specified area.

Syntax
BOOL GetAreaFormat (

        short areaCode,

        CRPESectionOptions *options );
Parameters
areaCode | Specifies the area code for the area for which you want to retrieve format information.
options | Specifies a pointer to CRPESectionOptions, which will contain the area format information retrieved.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetAreaFormatFormula

Use CRPEJob::GetAreaFormatFormula to retrieve the text of a conditional area format formula. Use this method in order to update the conditional area format formula and pass the changes back using CRPEJob::SetAreaFormatFormula.

Syntax
BOOL GetAreaFormatFormula(

        short areaCode,

        short formulaName,

        CString &formulaText );
Parameters
areaCode | Specifies the code for the report area for which you want to set formatting options. For information on area codes, see Working with section codes.
formulaName | Specifies the name of the formatting formula for which you want to supply a new string. Use one of the PEP_FFN_XXX Area/Section Format Formula Constants.
formulaText | Reference to the CString containing the new formula text.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetEnableEventInfo

Use CRPEJob::GetEnableEventInfo to retrieve information related to enabled/disabled events from CRPEEnableEventInfo.

Syntax

BOOL EnableEvent ( const CRPEEnableEventInfo *enableEventInfo );

Parameter

enableEventInfo

Specifies a pointer to CRPEEnableEventInfo, which contains the information that you want to retrieve.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetErrorCode

Use CRPEJob::GetErrorCode to retrieve the error code for the print job. When a call to another method fails, this call retrieves the error code that was generated so that you can take some action based on that error code.

Syntax

short GetErrorCode ();

Returns
  • Returns a Crystal Reports Class Library Error Codes.
  • Returns 0 (value of constant PEP_NOERROR) if no error has occurred.


CRPEJob::GetErrorText

Use CRPEJob::GetErrorText to retrieve the descriptive error message for the print job.

Syntax

CString GetErrorText ();

Returns

Returns a CString object containing the text description of the current Crystal Reports Class Library Error Codes, if an error has occurred.


CRPEJob::GetExportOptions

Use CRPEJob::GetExportOptions to get export options from the user before exporting the report. CRPEGetExportOptions can be used to present a series of dialog boxes that retrieve export options from your users. These options are used by the Crystal Report Engine to fill in CRPEExportOptions. Then the CRPEJob::ExportTo, can be used to set the print job destination using the information in the CRPEExportOptions structure.

Syntax

BOOL GetExportOptions ( CRPEExportOptions *options );

Parameter

options

Specifies a pointer to CRPEExportOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetFieldMappingType

Use CRPEJob::GetFieldMappingType to retrieve the field mapping type code.

Syntax

BOOL GetFieldMappingType ( WORD mappingType );

Parameter

mappingType | Specifies a pointer to the field mapping type code, which should be one of the following constants.
 | Constant | Description
 | PEP_FM_AUTO_FLD_MAP | Automatic field name mapping.
 | PEP_FM_CRPEP_PROMPT_FLD_MAP | CRPE provides dialog box to map field manually.
 | PEP_FM_EVENT_DEFINED_FLD_MAP | CRPE provides list of fields in the report and the new database.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetFormula

Use CRPEJob::GetFormula to return the formula text for the specified formula. CRPEJob::GetFormula is often used with CRPEJob::SetFormula, to identify and then change an existing formula in response to a user selection at print time.

Syntax
BOOL GetFormula (

        const _TCHAR *formulaName,

        CString &formulaText );
Parameters
formulaName | Specifies a pointer to the name of the formula for which you want to retrieve the formula string.
formulaText | Reference to the CString object loaded with the specified formula text when CRPEJob::GetFormula is completed successfully.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetFormulaSyntax

Use CRPEJob::GetFormulaSyntax to retrieve the syntax used by the formula addressed in the last formula API call.

Syntax

BOOL GetFormulaSyntax ( CRPEFormulaSyntax *formulaSyntax );

Parameters
Parameter | Description
formulaSyntax | Specifies a pointer to CRPEFormulaSyntax, which will contain the information that you want to retrieve.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

For running total condition formula:

  • formulaSyntax[0] is the syntax for the evalFormula, and
  • formulaSyntax[1] is the syntax for the resetFormula.


CRPEJob::GetGraphAxisInfo

Use CRPEJob::GetGraphAxisInfo to retrieve chart axis information for the specified chart.

Syntax
 BOOL GetGraphAxisInfo (

        short sectionN,

        short graphN,

        CRPEGraphAxisInfo *graphAxisInfo );
Parameters
sectionN | Specifies the section of the report containing the chart for which you want to retrieve chart axis information.
graphN | Specifies for which chart within the section you want to retrieve chart axis information. This value is 0-based. Charts are numbered based on their order of insertion into the report.
graphAxisInfo | Specifies a pointer to CRPEGraphAxisInfo, which will contain the information retrieved.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetGraphFontInfo

Use CRPEJob::GetGraphFontInfo to retrieve chart font information for the specified chart.

Syntax
BOOL GetGraphFontInfo (

        short sectionN,

        short graphN,

        WORD titleFontType,

        CRPEFontColorInfo *fontColourInfo );
Parameters
sectionN | Specifies the section of the report containing the chart for which you want to retrieve the font information.
graphN | Specifies for which chart within the section you want to retrieve the font information. This value is 0-based. Charts are numbered based on their order of insertion into the report.
titleFontType | Specifies the font type for the text. Use one of the PEP_GTF_XXX Graph Text Font Constants.
fontColourInfo | Specifies a pointer to CRPEFontColorInfo, which will contain the information retrieved.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetGraphOptionInfo

Use CRPEJob::GetGraphOptionInfo to obtain information about any of several chart options. These options include the minimum and maximum values that can appear on the chart, whether grid lines appear, whether risers are labeled, whether bar charts have horizontal or vertical bars, and whether a legend appears on the chart.

Syntax
BOOL GetGraphOptionInfo (

        short sectionN,

        short graphN,

        CRPEGraphOptionInfo * graphOptionInfo );
Parameters
sectionN | Specifies the section of the report containing the chart for which you want to retrieve chart option information.
graphN | Specifies for which chart within the section you want to retrieve chart option information. This value is 0-based. Charts are numbered based on their order of insertion into the report.
graphOptionInfo | Specifies a pointer to CRPEGraphOptionInfo.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetGraphTextDefaultOption

Use CRPEJob::GetGraphTextDefaultOption to determine whether the graph text default option is enabled or disabled for the specified chart.

Syntax
BOOL GetGraphTextDefaultOption (

        short sectionN,

        short graphN,

        WORD titleType,

        BOOL FAR *useDefault );
Parameters
Parameter | Description
sectionN | Specifies the section of the report containing the chart for which you want to retrieve chart title text default information.
graphN | Specifies the 0-based index number of the chart within the section for which you want to retrieve the chart title text default information. Charts are numbered based on their order of insertion into the report.
titleType | Specifies the title type. Use one of the PE_GTT_XXX Graph Title Type Constants.
useDefault | Specifies the Boolean value indicating whether or not chart title defaults are enabled.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetGraphTextInfo

Use CRPEJob::GetGraphTextInfo to determine what text appears with a chart. A chart can have a title, subtitle, footnote, title for groups, title for series, title for the X axis, title for the Y axis, and title for the Z axis (in 3D charts).

Syntax
 BOOL GetGraphTextInfo (

        short sectionN,

        short graphN,

        WORD titleType,

        HANDLE FAR * title,

        short FAR * titleLength );
Parameters
sectionN | Specifies the section of the report containing the chart for which you want to get chart text information.
graphN | Specifies the chart for which you want to get graph text information. This value is 0-based. Charts are numbered based on their order of insertion into the report.
titleType | Specifies the type of title. Use one of the PEP_GTT_XXX Graph Title Type Constants.
titleLength | Specifies a pointer to the handle of the title text.
titleLength | Specifies a pointer to the title length.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetGraphTypeInfo

Use CRPEJob::GetGraphTypeInfo to retrieve chart type information for the specified chart in the specified section. There are many types of charts available for use in Crystal Reports. Use this method to find out what type of chart is being displayed in the report.

Syntax
BOOL GetGraphTypeInfo (

        short sectionN,

        short graphN,

        CRPEGraphTypeInfo *graphTypeInfo );
Parameters
sectionN | Specifies the section of the report containing the chart for which you want to retrieve the type information.
graphN | Specifies for which chart within the section you want to retrieve the type information. This value is 0-based. Charts are numbered based on their order of insertion into the report.
graphTypeInfo | Specifies a pointer to CRPEGraphTypeInfo, which will contain the information retrieved.
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetGroupCondition

Use CRPEJob::GetGroupCondition to determine the group condition information for a selected group section in the specified report. Use this method to find out the group condition for a group section. Use CRPEJob::SetGroupCondition, to change the group condition once it is known.

Syntax
BOOL GetGroupCondition (

        short sectionCode,

        CString &conditionField,

        short *condition,

        short *sortDirection );
Parameters

sectionCode | Specifies the code for the report section for which you want to get the grouping condition. Use one of the following constants.
 | Constant | Description
 | PEP_GROUPHEADER | Sets the group condition for the Group Header section.
 | PEP_GROUPFOOTER | Sets the group condition for the Group Footer section.
conditionField | Reference to the name of the group summary field for which you want to get the grouping condition.
condition | Specifies a pointer to the type of field being used as the condition field and the condition that creates a new group. Use one of the following masks to separate the condition type from the group condition:
 | Constant | Description
 | PEP_GC_CONDITIONMASK | Obtains the group condition value. Use the bitwise AND (&) to combine this mask with the value of the condition parameter to obtain the group condition value.
 | PEP_GC_TYPEMASK | Obtains the type of field used for the group condition. Use the bitwise AND (&) to combine this mask with the value of the condition parameter to obtain a value representing the type of field used by the group condition.

For group condition field types other than Date and Boolean, the group condition value of the condition parameter is PEP_GC_ANYCHANGE. For a group condition field of the type Date or type DateTime, the group condition value will be one of the following constants.

Constant | Description
PEP_GC_DAILY | Triggers a grouping every time the date changes.
PEP_GC_WEEKLY | Triggers a grouping every time the date changes from one week to the next (a week runs from Sunday through Saturday).
PEP_GC_BIWEEKLY | Triggers a grouping every time the date changes from one two-week period to the next.
PEP_GC_SEMIMONTHLY | Triggers a grouping every time the date changes from one half-month period to the next.
PEP_GC_MONTHLY | Triggers a grouping every time the date changes from one month to the next.
PEP_GC_QUARTERLY | Triggers a grouping every time the date changes from one calendar quarter to the next.
PEP_GC_SEMIANNUALLY | Triggers a grouping every time the date changes from one half-year period to the next.
PEP_GC_ANNUALLY | Triggers a grouping every time the date changes from one year to the next.

For a group condition field of type Time or DateTime, the group condition value will be one of the following constants.

Constant | Description
PEP_GC_BYSECOND | Triggers a grouping every second.
PEP_GC_BYMINUTE | Triggers a grouping every minute.
PEP_GC_BYHOUR | Triggers a grouping every hour.
PEP_GC_BYAMPM | Triggers a grouping at 0000 and 1200 hours.

For a group condition field of the type Boolean, the group condition value will be one of the following constants.

Constant | Description
PEP_GC_TOYES | Triggers a grouping every time the sort-and-group-by field changes from No to Yes.
PEP_GC_TONO | Triggers a grouping every time the sort-and-group-by field changes from Yes to No.
PEP_GC_EVERYYES | Triggers a grouping every time the sort-and-group-by field value is Yes.
PEP_GC_EVERYNO | Triggers a grouping every time the sort-and-group-by field value is No.
PEP_GC_NEXTISYES | Triggers a grouping every time the next value in the sort-and-group-by field is Yes.
PEP_GC_NEXTISNO | Triggers a grouping every time the next value in the sort-and-group-by field is No.

The group condition field type portion of the condition parameter uses the following constants.

 | Constant | Description
 | PEP_GC_TYPEOTHER | Any field type other than Date or Boolean. The group condition portion of the condition parameter will be PEP_GC_ANYCHANGE.
 | PEP_GC_TYPEDATE | A Date field is used to create the group summary field.
 | PEP_GC_TYPEBOOLEAN | A Boolean field is used to create the group summary field.
 | PEP_GC_TYPETIME | A Time field is used to create the group summary field.
sortDirection | Specifies a pointer to the sort direction for the group summary field. Use one of the PEP_SF_XXX Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetGroupOptions

Use CRPEJob::GetGroupOptions to retrieve current settings for specified groups in a specified report.

Syntax
BOOL GetGroupOptions (

        short groupN,

        CRPEGroupOptions *groupOptions );
Parameters

groupN | Specifies the group number. The first level group is 0.
groupOptions | Specifies a pointer to CRPEGroupOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetGroupSelectionFormula

Use CRPEJob::GetGroupSelectionFormula to retrieve the formula text for the group selection formula. This method is often used with CRPEJob::SetGroupSelectionFormula, to identify and then change an existing group selection formula at print time (in response to a user selection).

Syntax

BOOL GetGroupSelectionFormula ( CString &formulaText );

Parameter

formulaText

Reference to the CString object containing the existing report group selection formula.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetJobHandle

Use CRPEJob::GetJobHandle to retrieve the job handle for the print job.

Syntax

short GetJobHandle ();

Returns

The print job handle for the CRPEJob object.


CRPEJob::GetJobStatus

Use CRPEJob::GetJobStatus to retrieve the current status of the print job.

Syntax

short GetJobStatus ( CRPEJobInfo *jobStatus );

Parameter

jobStatus

Specifies a pointer to CRPEJobInfo.

Returns

Returns one of the Job Status Constants, depending on the status of the current print job.

Remarks

You can use CRPEJob::GetJobStatus in a number of programming situations including the following.

  • To trigger error messages (when a print job fails due to insufficient memory, insufficient disk space, etc.).
  • To trigger screen displays (hourglass, series of graphics, etc.) that confirm to the user that work is in progress.
  • To find out whether a job was canceled by the user after CRPEJob::Start, was called.


CRPEJob::GetMargins

Use CRPEJob::GetMargins to retrieve the page margin settings for the specified report. Use this method to determine the current margin settings for a report. Use CRPEJob::SetMargins, to change report margins.

Syntax
BOOL GetMargins (

        short *left,

        short *right,

        short *top,

        short *bottom );
Parameters

left | Specifies a pointer to the current setting of the left margin in twips.
right | Specifies a pointer to the current setting of the right margin in twips.
top | Specifies a pointer to the current setting of the top margin in twips.
bottom | Specifies a pointer to the current setting of the bottom margin in twips.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

PEP_SM_DEFAULT is used to indicate printer default margins.


CRPEJob::GetNDetailCopies

Use CRPEJob::GetNDetailCopies to determine the number of copies of each Details section in the report to be printed. Use this method to find out how many times each Details section of the report will be printed and use CRPEJob::SetNDetailCopies, to change the number of times each Details section is printed.

Syntax

BOOL GetNDetailCopies ( short *nCopies );

Parameter

nCopies

Specifies a pointer to the current setting for the number of times the Details section of the report will be printed.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetNFormulas

Use CRPEJob::GetNFormulas to determine the number of formulas in the report. To retrieve the formula by number, use CRPEJob::GetNthFormula.

Syntax

short GetNFormulas ();

Returns
  • Returns the number of formulas in the report.
  • Returns 0 if no formulas exist in the report.
  • Returns -1 if an error occurs.


CRPEJob::GetNGroups

Use CRPEJob::GetNGroups to determine the number of group sections in the report.

Syntax

short GetNGroups ();

Returns
  • Returns the number of group sections in the report.
  • Returns -1 if an error occurs.


CRPEJob::GetNGroupSortFields

Use CRPEJob::GetNGroupSortFields to determine the number of group sort fields in the specified report. This method is typically used as one of a series of calls (GetNGroupSortFields, called once; CRPEJob::GetNthGroupSortField, called as many times as needed to identify the correct group sort field; and CRPEJob::SetNthGroupSortField, called once when the correct sort field is identified). This sequence of calls can be used to identify and then change an existing group sort field and/or sort order in response to a user selection at print time.

Syntax

short GetNGroupSortFields ();

Returns
  • Returns the number of group sort fields in the report.
  • Returns 0 if there are no group sort fields.
  • Returns -1 if an error occurs.


CRPEJob::GetNPages

Use CRPEJob::GetNPages to determine the number of pages in the report.

Syntax

short GetNPages ();

Returns

Returns the number of pages in the report.


CRPEJob::GetNParameterCurrentRanges

Use CRPEJob::GetNParameterCurrentRanges to determine the number of value ranges currently associated with the specified parameter field in the specified report.

Syntax
unsigned short GetNParameterCurrentRanges (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName );
Parameters

parameterFieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.

Returns
  • Returns the number of value ranges for the parameter field.
  • Returns -1 if the call fails.


CRPEJob::GetNParameterCurrentValues

Use CRPEJob::GetNParameterCurrentValues to determine the number of values currently stored in the specified parameter field of a report.

Syntax
unsigned short GetNParameterCurrentValues (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName );
Parameters

parameterFieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.

Returns
  • Returns the number of values currently stored in the parameter field.
  • Returns -1 if the call fails.


CRPEJob::GetNParameterDefaultValues

Use CRPEJob::GetNParameterDefaultValues to determine the number of default values for the specified parameter field in the specified report.

Syntax
short GetNParameterDefaultValues (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName );
Parameters

parameterFieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.

Returns
  • Returns the number of default values for the parameter field.
  • Returns 0 if there are no default values.
  • Returns -1 if an error occurs.


CRPEJob::GetNParameterFields

Use CRPEJob::GetNParameterFields to determine the number of parameter fields used in the report.

Syntax

short GetNParameterFields ();

Returns

Returns the number of parameter fields used in the report.

Remarks

To determine whether a specific parameter field is a stored procedure, use CRPEJob::GetNthParameterField.


CRPEJob::GetNSections

Use CRPEJob::GetNSections to determine the number of sections in the specified report.

Syntax

short GetNSections ();

Returns

Returns the number of sections in the report.

Remarks

By default, each report has five areas, each containing one of the following sections.

  • Report Header
  • Page Header
  • Details
  • Report Footer
  • Page Footer

If this method were applied to a default report, the return value would be 5 (five). As you add groups to your report or you add sections to one or more areas, the number of sections in the report increases.


CRPEJob::GetNSectionsInArea

Use CRPEJob::GetNSectionsInArea to determine the number of sections in the specified area of the report.

Syntax

short GetNSectionsInArea ( short areaCode );

Parameter

areaCode

Specifies a pointer to the area code for which you want to retrieve the number of sections.

Returns
  • Returns the number of sections in the specified area if the call is successful.
  • Returns -1 if the call fails.


CRPEJob::GetNSortFields

Use CRPEJob::GetNSortFields to determine the number of sort fields in the report.

Syntax

short GetNSortFields ();

Returns
  • Returns the number of sort fields defined in the report.
  • Returns 0 if there are no sort fields in the report.
  • Returns -1 if an error occurs.


CRPEJob::GetNSQLExpressions

Use CRPEJob::GetNSQLExpressions to determine the number of SQL expressions in the specified report.

Syntax

short GetNSQLExpressions ();

Returns
  • Returns the number of SQL expressions in the Report.
  • Returns 0 if there are no SQL expressions.
  • Returns -1 if an error occurs.


CRPEJob::GetNSubreportsInSection

Use CRPEJob::GetNSubreportsInSection to determine the number of subreports in the specified section.

Syntax

short GetNSubreportsInSection ( short sectionCode );

Parameter

sectionCode

Specifies the section code of the section for which you want a subreport count. See Working with section codes.

Returns
  • Returns the number of subreports in the report.
  • Returns 0 if there are no subreports.
  • Returns -1 if an error occurs.


CRPEJob::GetNTables

Use CRPEJob::GetNTables to determine the number of tables used in the report.

Syntax

short GetNTables ();

Returns

Returns the number of tables in the report.


CRPEJob::GetNthFormula

Use CRPEJob::GetNthFormula to obtain the formula name and formula text of a specific formula in the report. Once the formula name is obtained, formula text can be changed by using CRPEJob::SetFormula.

Syntax
BOOL GetNthFormula (

        short formulaN,

        CString &formulaName,

        CString &formulaText );
Parameters

formulaN | Specifies the number of the formula about which you want to retrieve information. The first formula added to your report is 0, the second is 1, etc.
formulaName | Reference to the CString containing the name of the formula specified.
formulaText | Reference to the CString containing the text of the formula specified.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetNthGroupSortField

Use CRPEJob::GetNthGroupSortField to determine the name of the group sort field and the sort direction (ascending or descending). This method is typically used as one of a series of calls (CRPEJob::GetNGroupSortFields, called once; CRPEJob::GetNthGroupSortField, called as many times as needed to identify the correct group sort field; and CRPEJob::SetNthGroupSortField, called once when the correct group sort field is identified). This series of methods can be used to identify and then change an existing group sort field and/or sort order in response to a user selection at print time.

Syntax
BOOL GetNthGroupSortField (

        short sortFieldN,

        CString &field,

        short *direction );
Parameters

sortFieldN | Specifies the number of the group sort field that you want to retrieve. The first group sort field is field 0. If the report has N sort fields, the method can be called with sortFieldN between 0 and N-1.
field | Reference to the CString object containing the name of the group sort field.
direction | Specifies a pointer to the value indicating the sort direction. Uses one of the PEP_SF_XXX Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetNthParameterCurrentRange

Use CRPEJob::GetNthParameterCurrentRange to retrieve the indicated value range from the specified parameter field in a report.

Syntax
BOOL GetNthParameterCurrentRange (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        short index,

        CRPEValueInfo *rangeStart,

        CRPEValueInfo *rangeEnd,

        short *rangeInfo );
Parameters

parameterField Name | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.
index | Specifies the index of the value range to be retrieved.
rangeStart | Specifies a pointer to CRPEValueInfo, which will contain the retrieved start range value. See Remarks below.
rangeEnd | Specifies a pointer to CRPEValueInfo, which will contain the retrieved end range value. See Remarks below.
rangeInfo | Specifies a pointer to the bit mapped value, which indicates whether the upper and/or lower bound of the range should be retrieved. Set rangeInfo to one of the following constants.
 | Constant | Value | Description
 | PEP_RI_INCLUDEUPPERBOUND | 1 | Returns rangeStart.
 | PEP_RI_INCLUDELOWERBOUND | 2 | Returns rangeEnd.
 | PEP_RI_INCLUDEUPPERBOUND OR PEP_RI_INCLUDELOWERBOUND | 3 | Returns rangeStart and rangeEnd.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Set rangeStart to NULL to retrieve maximum value only; rangeStart must be non-NULL if rangeEnd is NULL.
  • Set rangeEnd to NULL to retrieve minimum value only; rangeEnd must be non-NULL if rangeStart is NULL.
  • If both rangeStart and rangeEnd are specified (that is, non-NULL), then the valueType member of CRPEValueInfo for rangeStart and rangeEnd must be the same or an error code PEP_ERR_INCONSISTANTTYPES will be returned.


CRPEJob::GetNthParameterCurrentValue

Use CRPEJob::GetNthParameterCurrentValue to retrieve the indicated value from the specified parameter field of a specified report.

Syntax
BOOL GetNthParameterCurrentValue (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        short index,

        CRPEValueInfo *currentValue );
Parameters

parameterFieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.
index | Specifies the index number of the value to be retrieved.
currentValue | Specifies a pointer to CRPEValueInfo, which will contain the retrieved value.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetNthParameterDefaultValue

Use CRPEJob::GetNthParameterDefaultValue to retrieve the indicated default value for the specified parameter field in the specified report.

Syntax
BOOL GetNthParameterDefaultValue (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        short index,

        CRPEValueInfo *valueInfo );
Parameters

parameterFieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.
index | The index of the default parameter field value to be retrieved.
valuInfo | Specifies a pointer to CRPEValueInfo, in which the default value will be returned.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.

CRPEJob::GetNthParameterField

Use CRPEJob::GetNthParameterField to retrieve the name of the field, the data type, and information about the value set for the field. The name of the parameter field is returned as a string handle. This method is typically used as one of a series of calls (Returns -1 if an error occurs CRPEJob::GetNParameterFields, called once; CRPEJob::GetNthParameterField, called as many times as needed to identify the correct parameter field; and CRPEJob::SetNthParameterField, called once when the correct parameter field is identified). This series can be used in a Custom-Print Link to identify and then change an existing parameter field value in response to a user selection at print time.

Syntax
BOOL GetNthParameterField (

        short parameterN,

        CRPEParameterFieldInfo *parameterInfo );
Parameters

parameterN | Specifies the number of the parameter field about which you want to retrieve information.
parameterInfo | Specifies a pointer to CRPEParameterFieldInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetNthParameterType

Use CRPEJob::GetNthParameterType to retrieve the type or origin of a specified parameter field.

Syntax

short GetNthParameterType ( short index );

Parameter

index

Specifies the index of the parameter field for which you want to retrieve the type.

Returns
  • Returns one of the following values.

    Constant Description

    PEP_PO_REPORT

    Report

    PEP_PO_STOREDPROC

    Stored Procedure

    PEP_PO_QUERY

    Query

  • Returns -1 if the index is not valid.


CRPEJob::GetNthParameterValue Description

Use CRPEJob::GetNthParameterValueDescription to retrieve the description of the default value set for a parameter.

Syntax
 BOOL GetNthParameterValueDescription (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        short index,

        HANDLE *valueDesc,

        short *valueDescLength );
Parameters

parameterFieldName | Specifies a pointer to the parameterFieldName for which you want to retrieve the parameter value description.
reportName | Specifies a pointer to the report name.
index | Specifies the index.
valueDesc | Specifies a pointer to the handle of the value description to be retrieved.
valueDescLength | Specifies a pointer to the length of the value description.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.

CRPEJob::GetNthSortField

Use CRPEJob::GetNthSortField to retrieve the name of the sort field at the specified sort field position and the direction in which data in that field is sorted (ascending or descending).

Syntax
BOOL GetNthSortField (

        short sortFieldN,

        CString &field,

        short *direction );
Parameters

sortFieldN | Specifies the number of the sort field for which you want to retrieve information. The first sort field added to the report is field 0, the second is 1, etc.
field | Reference to the CString object containing the name of the sort field if the call is completed successfully.
direction | Specifies a pointer to the sort direction of the sort field if the call is completed successfully. Uses one of the PEP_SF_XXX Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetNthSQLExpression

Use CRPEJob::GetNthSQLExpression to retrieve a specified SQL expression.

Syntax
BOOL GetNthSQLExpression (

        short expressionN,

        CString &expressionName,

        CString &expressionText );
Parameters

expressionN | Index of the SQL expression that you want to retrieve.
expressionName | Reference to the CString object containing the SQL expression name.
expressionText | Reference to the CString object containing the SQL expression.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetNthSubreportInSection

Use CRPEJob::GetNthSubreportInSection to retrieve a handle that is required to retrieve the name of the subreport.

Syntax
DWORD GetNthSubreportInSection (

        short sectionCode,

        short subreportN );
Parameters

sectionCode | Specifies the code for the report section that contains the subreport. See Working with section codes.
subreportN | Specifies the 0-based number of the subreport in the specified section. The first report in the section will be 0, the second will be 1, etc.

Returns
  • Returns a handle to the specified subreport.
  • Returns 0 if there are no subreports in the specified section.
  • Returns -1 if an error occurs.


CRPEJob::GetNthTableLocation

Use CRPEJob::GetNthTableLocation to retrieve table location information for the specified table in the report. This method is typically used with CRPEJob::SetNthTableLocation, to identify the location of a table and then to change it.

Syntax
BOOL GetNthTableLocation (

        short tableN,

        CRPETableLocation *tableLocation );
Parameters

tableN | Specifies the 0-based number of the table for which you want to retrieve location information.
tableLocation | Specifies a pointer to CRPETableLocation.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetNthTableLogOnInfo

Use CRPEJob::GetNthTableLogOnInfo to retrieve SQL connection information for the specified table.

Syntax
BOOL GetNthTableLogonInfo (

        short tableN,

        CRPELogOnInfo *logonInfo );
Parameters

tableN | Specifies the 0-based number of the table from which you want to get logon information.
logonInfo | Specifies a pointer to CRPELogOnInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetNthTablePrivateInfo

Use CRPEJob::GetNthTablePrivateInfo to retrieve database information from CRPETablePrivateInfo.

Syntax
BOOL GetNthTablePrivateInfo (

        short tableN,

        CRPETablePrivateInfo *privateInfo );
Parameters

tableN | Specifies the 0-based number of the table from which you want to get private information.
privateInfo | Specifies a pointer to CRPETablePrivateInfo, which will contain the information retrieved.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetNthTableSessionInfo

Use CRPEJob::GetNthTableSessionInfo to retrieve session information for the specified Microsoft Access table. Many MS Access database tables require that a session be opened before the information in the table can be used. Use this method to obtain the session information (User ID and Session Handle) for a particular table.

Syntax
BOOL GetNthTableSessionInfo (

        short tableN,

        CRPESessionInfo *sessionInfo );
Parameters

tableN | Specifies the 0-based table number indicating the MS Access table in the report for which you want to obtain the session information.
sessionInfo | Specifies a pointer to CRPESessionInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.

CRPEJob::GetNthTableType

Use CRPEJob::GetNthTableType to retrieve table type information for the specified table.

Syntax
BOOL GetNthTableType (

        short tableN,

        CRPETableType *tableType );
Parameters

tableN | Specifies the 0-based table number indicating the table in the report for which you want to determine the type.
tableType | Specifies a pointer to CRPETableType.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetParameterMinMaxValue

Use CRPEJob::GetParameterMinMaxValue to retrieve the minimum and/or maximum possible values for a specified parameter in the specified report.

Syntax
BOOL GetParameterMinMaxValue (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        CRPEValueInfo *valueMin,

        CRPEValueInfo *valueMax );
Parameters

parameterFieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.
valueMin | Specifies a pointer to CRPEValueInfo, which contains the minimum value.
valueMax | Specifies a pointer to CRPEValueInfo, which contains the maximum value.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Set valueMin to NULL to retrieve maximum value only; must be non-NULL if valueMax is NULL.
  • Set valueMax to NULL to retrieve minimum value only; must be non-NULL if valueMin is NULL.


CRPEJob::GetParameterPickListOption

Use CRPEJob::GetParameterPickListOption to retrieve the parameter pick list options for a report. This method retrieves the values in CRPEParameterPickListOption.

Syntax
BOOL GetParameterPickListOption (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        CRPEParameterPickListOption *pickListOption );
Parameters

parameterFieldName | Specifies a pointer to the parameterFieldName for which you want to retrieve pick list options.
reportName | Specifies a pointer to the report name.
pickListOption | Specifies a pointer to CRPEParameterPickListOption, which will contain the information retrieved.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetParameterValueInfo

Use CRPEJob::GetParameterValueInfo to retrieve the CRPEParameterValueInfo structure associated with the specified parameter field in a report. This structure contains information about the values (editable, nullable field, multiple values, etc.) that can be stored in the specified field.

Syntax
BOOL GetParameterValueInfo (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        CRPEParamelterValueInfo *valueInfo );
Parameters

parameterFieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.
valueInfo | Specifies a pointer to CRPEParameterValueInfo, which contains the retrieved value information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

To determine whether a parameter field is a stored procedure, use CRPEJob::GetNthParameterField.

CRPEJob::GetPrintDate

Use CRPEJob::GetPrintDate to determine the print date (if any) that was specified with the report. Use this method to retrieve the print date and use CRPEJob::SetPrintDate, to pass a new print date.

Syntax
BOOL GetPrintDate (

        short *year,

        short *month,

        short *day );
Parameters

year | Specifies a pointer to the year for the current print date.
month | Specifies a pointer to the month for the current print date.
day | Specifies a pointer to the day for the current print date.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetPrintOptions

Use CRPEJob::GetPrintOptions to retrieve the print options specified for the report (the options that are set in the Print Setup common dialog box). Use this method to retrieve the print options from the report in order to update them and use CRPEJob::SetPrintOptions, to pass new print options back to the structure.

Syntax

BOOL GetPrintOptions ( CRPEPrintOptions *options );

Parameter

options

Specifies a pointer to CRPEPrintOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetReportOptions

Use CRPEJob::GetReportOptions to retrieve various options specified for the report from the Crystal Reports Designer File | Report Options menu CRPEReportOptions. Use this method to retrieve print options from the report and use CRPEJob::SetReportOptions, to pass new option settings back to the structure.

Syntax
BOOL GetReportOptions ( CRPEReportOptions *reportOptions );
Parameter

reportOptions

Specifies a pointer to the structure, CRPEReportOptions, containing the report options information to be retrieved.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetReportSummaryInfo

Use CRPEJob::GetReportSummaryInfo to retrieve summary information about a report such as the report title, author, and comments.

Syntax

BOOL GetReportSummaryInfo ( CRPEReportSummaryInfo *summaryInfo );

Parameter

summaryInfo

Specifies a pointer to CRPEReportSummaryInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetReportTitle

Use CRPEJob::GetReportTitle to retrieve the report title for the print job.

Syntax

BOOL GetReportTitle ( CString &title );

Parameter

title

Refers to the CString object containing the title of the report.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetSectionCode

Use CRPEJob::GetSectionCode to retrieve the section code for the specified section. A section code indicates the section type (Page Header, Details, etc.). If there are multiple group sections, it also identifies the group number, and if there are multiple sections in an area it identifies the section number.

Syntax

short GetSectionCode ( short sectionN );

Parameter

sectionN

Specifies the number of the section for which you want to retrieve the section code.

Returns
  • Returns the section code for the specified section.
  • Returns 0 if the call fails.


CRPEJob::GetSectionFormat

Use CRPEJob::GetSectionFormat to retrieve the section format settings for a selected section in the specified report and supply the information by assigning values to the members of the structure, CRPESectionOptions. Use this method in order to edit and update the section formats and use CRPEJob::SetSectionFormat, to pass information back to CRPESectionOptions.

Syntax
BOOL GetSectionFormat (

        short sectionCode,

        CRPESectionOptions *options );
Parameters

sectionCode | Specifies the code for the report section for which you want to obtain format information. Use one of the PEP_XXX Section Codes Constants.
options | Specifies a pointer to CRPESectionOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.

CRPEJob::GetSectionFormatFormula

Use CRPEJob::GetSectionFormatFormula to retrieve the text of a conditional section format formula as a string handle. Use this method to update the conditional section format formula and pass the changes back using CRPEJob::SetSectionFormatFormula.

Syntax
BOOL GetSectionFormatFormula (

        short areaCode,

        short sectionCode,

        short formulaName,

        CString &formulaText );
Parameters

areaCode | Specifies the code for the report area for which you want to set formatting options. For information on area codes, see Working with section codes.
sectionCode | Specifies the code for the report section(s) for which you want to get section format information. See the table of section constants supplied in Working with section codes.
formulaName | Specifies the name of the PEP_FFN_XXX Area/Section Format Formula Constants.
formulaText | Refers to the Cstring object passed with the specified formula text when CRPEJob::GetSectionFormatFormula has completed successfully.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Not all formula names apply to all sections.
  • Use the value returned by textLength to allocate memory for a buffer. Use CRPEngine::GetHandleString, to fill the buffer with the actual text of the formula.


CRPEJob::GetSectionHeight

Use CRPEJob::GetSectionHeight to retrieve the section height information for the specified section. Use this method to retrieve the section height, and use CRPEJob::SetSectionHeight, to pass new section height information.

Syntax
BOOL GetSectionHeight (

        short sectionCode,

        short *height );
Parameters

sectionCode | Specifies the code for the report sections for which you want to retrieve information.
height | Specifies a pointer to the section height (in twips) returned by this call.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetSelectedPrinter

Use CRPEJob::GetSelectedPrinter to determine which printer has been specified with the report. If a non-default printer is specified in the report, CRPEJob::GetSelectedPrinter retrieves information about that printer. This can be used, for example, to determine if the user has access to the printer specified in the report and to choose another printer if necessary.

Syntax
BOOL GetSelectedPrinter (

        CString &driverName,

        CString &printerName,

        CString &portName,

        DEVMODE **mode );
Parameters

driver Name | Reference to the CString object containing the name of the printer driver for the currently selected printer in the report.
printer Name | Reference to the CString object containing the name of the printer currently selected in the report.
portName | Reference to the CString object containing the name of the port to which the currently selected printer is attached (for example, "LPT1").
mode | Specifies a pointer to a pointer to the Windows API structure DEVMODE that contains information on the currently selected printer, if the CRPEJob::GetSelectedPrinter method is completed successfully. For more information on the DEVMODE structure, see DEVMODE.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetSelectionFormula

Use CRPEJob::GetSelectionFormula to retrieve the formula text for the record selection formula. CRPEJob::GetSelectionFormula is often used with CRPEJob::SetSelectionFormula, to identify and then change an existing selection formula in response to a user selection at print time.

Syntax
BOOL GetSelectionFormula (

        CString &formulaText );
Parameter

formulaText

Reference to the CString object containing the existing selection formula for the report.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetSQLExpression

Use CRPEJob::GetSQLExpression to retrieve the text of a specific SQL expression, given an expression name.

Syntax
BOOL GetSQLExpression (

        const _TCHAR *expressionName,

        CString &expressionText );
Parameters

expressionName | Specifies a pointer to the expression name.
expressionText | Reference to the CString that contains the expression text.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetSQLQuery

Use CRPEJob::GetSQLQuery to retrieve the SQL query that will be sent to the database server. This method can be used with CRPEJob::SetSQLQuery, to retrieve and then change the SQL query for the report.

Syntax

BOOL GetSQLQuery ( CString &query );

Parameter

query

Reference to the CString containing the text of the SQL query being sent to the server if the call is completed successfully.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetSubreportInfo

Use CRPEJob::GetSubreportInfo to retrieve information about the specified subreport.

Syntax
BOOL GetSubreportInfo (

        DWORD subreportHandle,

        CRPESubreportInfo *subreportInfo );
Parameters

subreportHandle | Specifies the handle of the subreport about which you want to retrieve information.
subreportInfo | Specifies a pointer to CRPESubreportInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetTrackCursorInfo

Use CRPEJob::GetTrackCursorInfo to retrieve track cursor details for the preview window.

Syntax

BOOL GetTrackCursorInfo ( CRPETrackCursorInfo *cursorInfo );

Parameter

cursorInfo

Specifies a pointer to CRPETrackCursorInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetWindowHandle

Use CRPEJob::GetWindowHandle to retrieve the Windows handle for the preview window. When this method returns successfully, you can use the HWND value with any Windows API function that requires a window handle as a parameter.

Syntax

HWND GetWindowHandle ();

Returns

The Microsoft Windows Handle for the preview window.


CRPEJob::GetWindowOptions

Use CRPEJob::GetWindowOptions to retrieve the options associated with a specified window object. This information can then be changed and sent back to CRPEWindowOptions by using CRPEJob::SetWindowOptions. Use this method to customize the features of the window object.

Syntax

BOOL GetWindowOptions ( CRPEWindowOptions *windowOptions );

Parameter

windowOptions

Specifies a pointer to CRPEWindowOptions, which contains the information that you want to retrieve.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::HasSavedData

Use CRPEJob::HasSavedData to determine whether a report has saved data. This method can be used to determine whether it is necessary to refresh the data before printing the report.

Syntax

BOOL HasSavedData ( BOOL *hasSavedData );

Parameter

hasSavedData

Specifies a pointer to a memory address that indicates whether there is data saved with the report.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::IsJobFinished

Use CRPEJob::IsJobFinished to retrieve a Boolean value that indicates whether processing has finished for the print job. You can use this method any time that you have a call that is contingent on a print job being finished.

Syntax

BOOL IsJobFinished ();

Returns
  • TRUE if processing has finished.
  • FALSE if the job is in progress.


CRPEJob::NextWindowMagnification

Use CRPEJob::NextWindowMagnification to switch to the next preview window magnification in order. Use this method to cycle through the three levels (Full page, Fit one side, and Fit both sides) of preview window magnification, whenever the report has been printed to a preview window.

Syntax

BOOL NextWindowMagnification ();

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::OpenSubreportJob

Use CRPEJob::OpenSubreportJob to open the named subreport and return a pointer to a CRPEJob object for that subreport. The CRPEJob object can be used to make subsequent changes to the subreport.

Syntax
CRPEJob *OpenSubreportJob ( const _TCHAR *subreportName );
Parameter

subreportName

Specifies a pointer to the name of the subreport that you want to access. This name is retrieved using CRPEJob::GetSubreportInfo.

Returns

A pointer to a class CRPEJob : public CObject, object for the subreport.


CRPEJob::OutputToPrinter

Use CRPEJob::OutputToPrinter to set the output of the print job to the printer with the specified number of copies. This method does not print the report, but specifies that when the report is printed, it will be sent to a printer. Use CRPEJob::Start to print the report.

Syntax

BOOL OutputToPrinter ( short nCopies = 1 );

Parameter

nCopies

Specifies how many copies of the report are to be printed. Default is 1 copy.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::OutputToWindow

Use CRPEJob::OutputToWindow to set the output of the print job to the preview window that will have the specified attributes. It does not print the report, but specifies that when the report is printed, it will also appear in a preview window. To print the report, use CRPEJob::Start.

Syntax

For an SDI application

BOOL OutputToWindow (

        const _TCHAR *title,

        int left,

        int top,

        int width,

        int height,

        int style,

        CWnd *parentWindow );

For an MDI application

BOOL OutputToWindow (

        const _TCHAR *title,

        int left,

        int top,

        int width,

        int height,

        int style,

        CMDIFrameWnd *parentWindow );
Parameters

title | Specifies a pointer to the title that you want to appear in the title bar.
left | Specifies the x coordinate of the upper left-hand corner of the preview window, in device coordinates.
top | Specifies the y coordinate of the upper left-hand corner of the preview window, in device coordinates.
width | Specifies the width of the preview window, in device coordinates.
height | Specifies the height of the preview window, in device coordinates.
style | Specifies the style of the window being created. Style setting can be combined using the bitwise Or operator (|). Refer to the CWnd class in the Microsoft Foundation Class Library reference for possible window styles.
parentWindow | Specifies a pointer to the CWnd object (in an SDI application) or the CMDIFrameWnd object (in an MDI application) for the window that is the parent of the preview window. Specify NULL if the preview window will not have a parent window.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

This method is overloaded to handle both SDI and MDI applications.


CRPEJob::PrintControlsShowing

Use CRPEJob::PrintControlsShowing to determine if the print controls will be displayed in the preview window. Use CRPEJob::ShowPrintControls, to specify whether or not the print controls will appear in the preview window.

Syntax

BOOL PrintControlsShowing ( BOOL *controlsShowing );

Parameter

controlsShowing

Specifies a pointer to a TRUE value if the print controls will be shown in the preview window and a FALSE value if they will be hidden.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::PrintWindow

Use CRPEJob::PrintWindow to send the report displayed in the preview window to the printer. If you are customizing preview window controls, use this method to enable the user to preview the report in the preview window, and then, if everything looks satisfactory, to send the report to the printer in response to a user event (button click, menu command, etc.).

Syntax

BOOL PrintWindow ();

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::ReimportSubreport

Use CRPEJob::ReimportSubreport to reimport a subreport into the specified main report.

Syntax
BOOL ReimportSubreport ( DWORD subreportHandle,

        BOOL FAR *linkChanged,

        BOOL FAR *reimported );
Parameters

Parameter | Description
subreportHandle | Specifies the handle of the subreport that you want to reimport.
linkChanged | Specifies a pointer to a Boolean value indicating whether or not the link has changed. See Remarks below.
reimported | Specifies a pointer to a Boolean value indicating whether or not the subreport has been reimported. See Remarks below.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Parameter linkChanged
      • will be set to FALSE if the subreport is reloaded and the links are fixed.
      • will be set to TRUE if the subreport is reloaded but missing links.
  • Parameter reimported
      • will be set to FALSE if the subreport is up-to-date, or if the reimport failed due to an invalid path or other error.
      • will be set to TRUE if the subreport was reloaded with links fixed or missing.


CRPEJob::SelectPrinter

Use CRPEJob::SelectPrinter to specify the printer and/or print characteristics for the print job. You can use this method to enable the user to select a printer other than the default printer at print time. One way of doing this is to have your application call the Windows common Print Setup dialog box.

Syntax
BOOL SelectPrinter (

        const _TCHAR *driverName,

        const _TCHAR *printerName,

        const _TCHAR *portName,

        const DEVMODE *mode = 0 );
Parameters

driverName | Specifies a pointer to the name of the printer driver for the printer being selected.
printerName | Specifies a pointer to the name of the printer being selected (as indicated in the Printers Control Panel).
portName | Specifies a pointer to the name of the port to which the printer is attached (for example, "LPT1").
mode | Specifies a pointer to a Windows API DEVMODE structure. The default implementation of CRPEJob::SelectPrinter ignores this parameter. For more information, see DEVMODE.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetAllowPromptDialog

Use CRPEJob::SetAllowPromptDialog to specify whether prompting for parameter values is allowed during printing.

Syntax

BOOL SetAllowPromptDialog ( BOOL showPromptDialog );

Parameter

showPromptDialog

If showPromptDialog is set to TRUE, then prompting is allowed.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetAreaFormat

Use CRPEJob::SetAreaFormat to set format information for the specified area.

Syntax
BOOL SetAreaFormat (

        short areaCode,

        CRPESectionOptions *options );
Parameters

areaCode | Specifies the area code for the area for which you want to set format information.
options | Specifies a pointer to CRPESectionOptions, which will contain the new area format information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetAreaFormatFormula

Use CRPEJob::SetAreaFormatFormula to change the specified area format formula to the formula string that you supply as a parameter. This method will change only the text of a formula that already exists in the report; you cannot use it to add a formula. When you give the user the ability to change the formula at print time, your link must include code to replace formulaString with a user-generated value.

Syntax
BOOL SetAreaFormatFormula (

        short areaCode,

        short formulaName,

        CString formulaText );
Parameters

areaCode | Specifies the code for the report area for which you want to set formatting options.
formulaName | Specifies the name of the formatting formula for which you want to supply a new string. Use one of the PEP_FFN_XXX Area/Section Format Formula Constants.
formulaText | The Cstring object passed here is loaded with the specified formula text when CRPEJob::SetAreaFormatFormula completes successfully.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • This method should be called before CRPEJob::Start or the results may be inconsistent or unexpected.
  • Not all parameters apply to all areas.


CRPEJob::SetDialogParentWindow

Use CRPEJob::SetDialogParentWindow to specify the handle for the parent window of a preview window that is an MDI child.

Syntax

BOOL SetDialogParentWindow ( CWnd *parentWindow );

Parameter

parentWindow

Specifies a pointer to the CWnd object that is to be the parent of the preview window when the report is printed to a preview window.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetEventCallback

Use CRPEJob::SetEventCallback to set event callback information for a job. The Crystal Reports Engine can determine when certain events have happened or are about to happen and provide notice so that appropriate response can be made.

Syntax
BOOL SetEventCallback (

        BOOL ( CALLBACK * callbackProc )

                ( short eventID, void *param, void *userData ),

        void *userData );
Parameters

callbackProc | The CALLBACK procedure that will handle your Crystal Report Engine events. This should be a pointer to a standard Windows CALLBACK procedure. Refer to the Microsoft Windows SDK for information on creating CALLBACK procedures.
userData | Specifies a pointer to the information that you want to pass to the Event handling callback procedure. The pointer will be available in the user data member of callbackProc. This value can be 0.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

See the list of Event Id Constants. Also, for additional information, see the more detailed listing which follows PESetEventCallback.


CRPEJob::SetFieldMappingType

Use CRPEJob::SetFieldMappingType to set the field mapping type code.

Syntax

BOOL SetFieldMappingType ( WORD mappingType );

Parameter

mappingType | Specifies the field mapping type code. Use one of the following constants.
 | Constant | Description
 | PEP_FM_AUTO_FLD_MAP | Automatic field name mapping.
 | PEP_FM_CRPEP_PROMPT_FLD_MAP | CRPE provides dialog box to map field manually.
 | PEP_FM_EVENT_DEFINED_FLD_MAP | CRPE provides list of fields in the report and the new database.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetFont

Use CRPEJob::SetFont to set the font and font characteristics for the specified section. Use it any time that you want to change a default font at runtime in response to user input, or to specify a built-in printer font.

Syntax
BOOL SetFont (

        short sectionCode,

        short scopeCode,

        const _TCHAR *faceName,

        short fontFamily,

        short fontPitch,

        short charSet,

        short pointSize,

        short isItalic,

        short isUnderlined,

        short isStruckOut,

        short weight );
Parameters

sectionCode | Specifies the section of the report for which you want to set the font. Use one of the PEP_XXX Section Codes Constants.
scopeCode | Specifies whether the font selected is to apply to fields, to text, or to both. To specify both, use the bitwise "Or" operator (|). Use one of the following constants.
 | Constant | Description
 | PEP_FIELDS | Sets the default font for fields in the report section specified.
 | PEP_TEXT | Sets the default font for all text (that has not been entered as a text field value) in the report section specified.
faceName | Specifies a pointer to the actual face name of the font that you want to use. The face name you pass can typically come from a font dialog box, be hard coded in the application, or be chosen by the application from the fonts supported on the printer (for example, "Times New Roman").
fontFamily | Specifies the font family for the font that you want to use. Use one of the following constants.
 | Constant | Description
 | FF_DONTCARE | No font family or family does not matter.
 | FF_ROMAN | Variable pitch font with serifs.
 | FF_SWISS | Fixed pitch font without serifs.
 | FF_MODERN | Fixed pitch font with or without serifs.
 | FF_SCRIPT | Handwriting-like font.
 | FF_DECORATIVE | Fancy display font.
fontPitch | Specifies the font pitch that you want to use. Use one of the following constants.
 | Constant | Description
 | DEFAULT_PITCH | Retains the default pitch for the font.
 | FIXED_PITCH | Fixed pitch, each character is the same width.
 | VARIABLE_PITCH | Variable pitch, the width of each character varies.
charSet | Specifies the character set that you want to use. Use one of the following constants.
 | Constant
 | ANSI_CHARSET |
 | SYMBOL_CHARSET |
 | HANGEFUL_CHARSET |
 | OEM_CHARSET |
 | DEFAULT_CHARSET |
 | SHIFTJIS_CHARSET |
 | CHINESEBIG5_CHARSET |
pointSize | Specifies the desired point size for the selected font. Use 0 to indicate no change.
isItalic | Specifies whether the font selected should be italicized. Use 1 for italics, 0 for no italics, or PEP_UNCHANGED to leave the italics as set up in the report.
isUnderlined | Specifies whether the font should be underlined. Use 1 to underline, 0 for no underline, or PEP_UNCHANGED to leave underline settings as specified in the report.
isStruckOut | Specifies whether the font should appear struck-out. Use 1 for strike-out, 0 for no strike out, or PEP_UNCHANGE to leave strike-out settings as specified in the report.
weight | Specifies the weight of the font. Use one of the following constants.
 | Constant
 | FW_DONTCARE
 | FW_EXTRALIGHT
 | FW_NORMAL
 | FW_SEMIBOLD
 | FW_EXTRABOLD
 | FW_ULTRALIGHT
 | FW_DEMIBOLD
 | FW_BLACK
 | FW_THIN
 | FW_LIGHT
 | FW_MEDIUM
 | FW_BOLD
 | FW_HEAVY
 | FW_REGULAR
 | FW_ULTRABOLD

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetFormula

Use CRPEJob::SetFormula to set the formula text for the specified formula. CRPEJob::SetFormula is often used with CRPEJob::GetFormula, to identify and then change an existing formula in response to a user selection at print time.

Syntax
BOOL SetFormula (

        const _TCHAR *formulaName,

        const _TCHAR *formulaText );
Parameters

formulaName | Specifies a pointer to the name of the formula for which you want to assign new formula text.
formulaText | Specifies a pointer to the actual formula text that replaces the existing formula string.

Returns
  • TRUE if the call is successful.
  • FALSE if the named formula does not exist, if there is an error in the formula, or if the call fails.


CRPEJob::SetFormulaSyntax

Use CRPEJob::SetFormulaSyntax to set the syntax to use in the next (and all successive) formula API calls.

Syntax

BOOL SetFormulaSyntax ( CRPEFormulaSyntax *formulaSyntax );

Parameter

Parameter | Description
formulaSyntax | Specifies a pointer to CRPEFormulaSyntax which will contain the information that you set. See Remarks below.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

For running total condition formula:

  • formulaSyntax[0] is the syntax for the evalFormula, and
  • formulaSyntax[1] is the syntax for the resetFormula.


CRPEJob::SetGraphAxisInfo

Use CRPEJob::SetGraphAxisInfo to set chart axis information for the specified chart.

Syntax
 BOOL SetGraphAxisInfo (

        short sectionN,

        short graphN,

        CRPEGraphAxisInfo *graphAxisInfo );
Parameters

sectionN | Specifies the section of the report containing the chart for which you want to set chart axis information.
graphN | Specifies for which chart within the section you want to set chart axis information. This value is 0-based. Charts are numbered based on their order of insertion into the report.
graphAxisInfo | Specifies a pointer to CRPEGraphAxisInfo, which will contain the new information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetGraphFontInfo

Use CRPEJob::SetGraphFontInfo to set graph font information for the specified chart.

Syntax
BOOL SetGraphFontInfo (

        short sectionN,

        short graphN,

        WORD titleFontType,

        CRPEFontColorInfo *fontColourInfo );
Parameters

sectionN | Specifies the section of the report containing the chart for which you want to set the font information.
graphN | Specifies for which chart within the section you want to set the font information. This value is 0-based. Charts are numbered based on their order of insertion into the report.
titleFontType | Specifies the font type for the text. Use one of the PEP_GTF_XXX Graph Text Font Constants.
fontColourInfo | Specifies a pointer to CRPEFontColorInfo, which will contain the new information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetGraphOptionInfo

Use CRPEJob::SetGraphOptionInfo to change any of several chart options. These options include the minimum and maximum values that can appear on the chart, whether grid lines appear, whether risers are labeled, whether bar graphs have horizontal or vertical bars, and whether a legend appears on the chart.

Syntax
BOOL SetGraphOptionInfo (

        short sectionN,

        short graphN,

        CRPEGraphOptionInfo *graphOptionInfo );
Parameters

sectionN | Specifies the section of the report containing the chart for which you want to set chart options.
graphN | Specifies for which chart within the section you want to set chart options. This value is 0-based. Charts are numbered based on their order of insertion into the report.
graphOptionInfo | Specifies a pointer to CRPEGraphOptionInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetGraphTextDefaultOption

Use CRPEJob::SetGraphTextDefaultOption to enable or disable chart title defaults.

Syntax
BOOL SetGraphTextDefaultOption (

        short sectionN,

        short graphN,

        WORD titleType,

        BOOL useDefault );
Parameters

Parameter | Description
sectionN | Specifies the section of the report containing the chart for which you want to set chart title text default information.
graphN | Specifies the 0-based index number of the chart within the section for which you want to set the chart title text default information. Charts are numbered based on their order of insertion into the report.
titleType | Specifies the title type. Use one of the PE_GTT_XXX Graph Title Type Constants.
useDefault | Specifies the Boolean value indicating whether or not chart title defaults are enabled.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetGraphTextInfo

Use CRPEJob::SetGraphTextInfo to set or change the text that appears with a chart. A chart can have a title, subtitle, footnote, title for groups, title for series, title for the X axis, title for the Y axis, and title for the Z axis (in 3D graphs).

Syntax
BOOL SetGraphTextInfo (

        short sectionN,

        short graphN,

        WORD titleType,

        LPCSTR title );
Parameters

sectionN | Specifies the section of the report containing the chart for which you want to set the text information.
graphN | Specifies for which chart within the section you want to set the text information. This value is 0-based. Charts are numbered based on their order of insertion into the report.
titleType | Specifies the title type. Use one of the PEP_GTT_XXX Graph Title Type Constants.
title | Specifies a pointer to the CString object containing the title text.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetGraphTypeInfo

Use CRPEJob::SetGraphTypeInfo to set the chart type information (based on one of the available chart types) for the specified chart in the specified section. Use this method to change the type of chart that is displayed in a report.

Syntax
        BOOL SetGraphTypeInfo (

        short sectionN,

        short graphN,

        CRPEGraphTypeInfo *graphTypeInfo );
Parameters

sectionN | Specifies the section of the report containing the chart for which you want to set the type information.
graphN | Specifies for which chart within the section you want to set the type. This value is 0-based. Charts are numbered based on their order of insertion into the report.
graphTypeInfo | Specifies a pointer to CRPEGraphTypeInfo, which will contain the new information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetGroupCondition

Use CRPEJob::SetGroupCondition to set the condition of the grouping for the specified group section. This method can only replace the group condition for an existing group. It cannot create a new group. Use this method whenever you want to change the grouping at print time (for example, to print a report grouped in several different ways).

Syntax
BOOL SetGroupCondition (

        short sectionCode,

        const _TCHAR *conditionField,

        short condition,

        short sortDirection );
Parameters

sectionCode | Specifies the code for the group section for which you want to set the group condition. Use one of the following constants.
 | Constant | Description
 | PEP_GROUPHEADER | Sets the group condition for the Group Header section.
 | PEP_GROUPFOOTER | Sets the group condition for the Group Footer section.
conditionField | Specifies a pointer to the field that triggers a summary whenever its value changes. Use the name of the field as indicated in the report file.
condition | Specifies the condition that needs to be met for Date and Boolean fields. For all field types (except Date and Boolean), use PEP_GC_ANYCHANGE as the condition parameter. Use one of the following constants for Date and Boolean field types.
 | Constant (Date fields only) | Description
 | PEP_GC_DAILY | Triggers a grouping every time the date changes.
 | PEP_GC_WEEKLY | Triggers a grouping every time the date changes from one week to the next (a week runs from Sunday through Saturday).
 | PEP_GC_BIWEEKLY | Triggers a grouping every time the date changes from one two-week period to the next.
 | PEP_GC_SEMIMONTHLY | Triggers a grouping every time the date changes from one half-month period to the next.
 | PEP_GC_MONTHLY | Triggers a grouping every time the date changes from one month to the next.
 | PEP_GC_QUARTERLY | Triggers a grouping every time the date changes from one calendar quarter to the next.
 | PEP_GC_SEMIANNUALLY | Triggers a grouping every time the date changes from one half-year period to the next.
 | PEP_GC_ANNUALLY | Triggers a grouping every time the date changes from one year to the next.
 | Constant (Boolean fields only) | Description
 | PEP_GC_TOYES | Triggers a grouping every time the sort-and-group-by field changes from No to Yes.
 | PEP_GC_TONO | Triggers a grouping every time the sort-and-group-by field changes from Yes to No.
 | PEP_GC_EVERYYES | Triggers a grouping every time the sort-and-group-by field value is Yes.
 | PEP_GC_EVERYNO | Triggers a grouping every time the sort-and-group-by field value is No.
 | PEP_GC_NEXTISYES | Triggers a grouping every time the next value in the sort-and-group-by field is Yes.
 | PEP_GC_NEXTISNO | Triggers a grouping every time the next value in the sort-and-group-by field is No.
sortDirection | Specifies one of the PEP_SF_XXX Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetGroupOptions

Use CRPEJob::SetGroupOptions to set various grouping options for the specified group. This method sets the formula text for the group selection formula. CRPEJob::SetGroupSelectionFormula is often used with CRPEJob::GetGroupSelectionFormula, to identify and then change an existing group selection formula in response to a user selection at print time.

Syntax
BOOL SetGroupOptions (

        short groupN,

        CRPEGroupOptions *groupOptions );
Parameters

groupN | Specifies the 0-based group level number.
groupOptions | Specifies a pointer to CRPEGroupOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • This method should be called before CRPEJob::Start, or the results may be inconsistent or unexpected.
  • If you are using CRPEJob::SetGroupOptions, to set the top/bottom N sort field, all the group sort fields related to the group will be deleted and a new one specified by the group options will be added.


CRPEJob::SetGroupSelectionFormula

Use CRPEJob::SetGroupSelectionFormula to set the formula text for the group selection formula. This method is often used with CRPEJob::GetGroupSelectionFormula, to identify and then change an existing group selection formula in response to a user selection at print time.

Syntax

BOOL SetGroupSelectionFormula ( const _TCHAR *formulaText );

Parameter

formulaText

Specifies a pointer to the new group selection formula to be assigned to the report.

Returns
  • TRUE if the call is successful.
  • FALSE if there is an error in the formula or if the call fails.


CRPEJob::SetMargins

Use CRPEJob::SetMargins to set the page margins for the print job. Use this method any time that you want to allow the user to change margins.

Syntax
BOOL SetMargins (

        short left,

        short right,

        short top,

        short bottom );
Parameters

left | Specifies the left margin in twips.
right | Specifies the right margin in twips.
top | Specifies the top margin in twips.
bottom | Specifies the bottom margin in twips.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

For any of the parameters, PM_SM_DEFAULT can be used to specify that the report use default printer margins.


CRPEJob::SetNDetailCopies

Use CRPEJob::SetNDetailCopies to set the number of times the Details section of the report is to be printed. For example, you can use this method to print multiple copies of labels for a customer, multiple copies of a purchase order, or multiple copies of anything set up in the Details section of the report.

Syntax

BOOL SetNDetailCopies ( short nCopies );

Parameter

nCopies

Specifies the number of copies of the Details section of the report to be printed.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetNthGroupSortField

Use CRPEJob::SetNthGroupSortField to set the name of the group sort field and the sort direction (ascending or descending). This method is typically used as one of a series of calls (CRPEJob::GetNGroupSortFields, called once; CRPEJob::GetNthGroupSortField, called as many times as needed to identify the correct group sort field; and CRPEJob::SetNthGroupSortField called once when the correct group sort field is identified). This series of methods can be used to identify and then change an existing group sort field and/or sort order in response to a user selection at print time. This method does not create a new group, but will sort an existing group summary field.

Syntax
BOOL SetNthGroupSortField (

        short sortFieldN,

        const _TCHAR *field,

        short direction );
Parameters

sortFieldN | Specifies the number of the group sort field that you want to set. The first group sort field added to the report is field 0, the second is 1, etc. If the report has N group sort fields, the function can be called with this parameter between 0 and N-1 to replace an existing group sort field. Call the function with this parameter equal to N to add a new group sort field.
field | Specifies a pointer to the name of the group field to be sorted.
direction | Specifies the sort direction. Uses one of the PEP_SF_XXX Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetNthParameterDefaultValue

Use CRPEJob::SetNthParameterDefaultValue to set the indicated default value for the specified parameter field in the specified report.

Syntax
BOOL SetNthParameterDefaultValue (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        short index,

        CRPEValueInfo *valueInfo );
Parameters

parameterFieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.
index | Specifies the index number of the default value that you want to set.
valueInfo | Specifies a pointer to CRPEValueInfo, which will contain the new value.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetNthParameterField

Use CRPEJob::SetNthParameterField to set a value for the specified parameter field. This method is typically used as one of a series of calls (CRPEJob::GetNParameterFields, called once; CRPEJob::GetNthParameterField, called as many times as needed to identify the correct parameter field; and CRPEJob::SetNthParameterField, called once when the correct parameter field is identified). This series can be used in a Custom-Print Link to identify and then change an existing parameter field value in response to a user selection at print time.

Syntax
BOOL SetNthParameterField (

        short parameterN,

        const CRPEParameterFieldInfo *parameterInfo );
Parameters

parameterN | Specifies the number of the parameter field for which you want to set information.
parameterInfo | Specifies a pointer to CRPEParameterFieldInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetNthParameterValueDescription

Use CRPEJob::SetNthParameterValueDescription to set the description of the default value for a parameter.

Syntax
 BOOL SetNthParameterValueDescription (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        short index,

        _TCHAR *valueDesc );
Parameters

parameterFieldName | Specifies a pointer to the parameterFieldName for which you want to set the parameter value description.
reportName | Specifies a pointer to the report name.
index | Specifies the index.
valueDesc | Specifies a pointer to the value description to be set.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetNthSortField

Use CRPEJob::SetNthSortField to sort report data according to the specified field and direction.

Syntax
BOOL SetNthSortField (

        short sortFieldN,

        const _TCHAR *field,

        short direction );
Parameters

sortFieldN | Specifies the number of the sort field that you want to set. The first sort field added to the report is field 0, the second is 1, etc. If the report has N sort fields, the function can be called with this parameter between 0 and N-1 to replace an existing sort field. Call the function with this parameter equal to N to add a new sort field.
field | Specifies a pointer to the name of the field to be sorted.
direction | Specifies the sort direction. Use one of the PEP_SF_XXX Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.

CRPEJob::SetNthTableLocation

Use CRPEJob::SetNthTableLocation to set the table location information for the specified table in the report. This method is typically combined with CRPEJob::GetNthTableLocation, to identify the location of a table and CRPEJob::SetNthTableLocation to change it.

Syntax
BOOL SetNthTableLocation (

        short tableN,

        const CRPETableLocation *tableLocation );
Parameters

tableN | Specifies the 0-based number of the table for which you want to set a new location.
tableLocation | Specifies a pointer to CRPETableLocation.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetNthTableLogOnInfo

Use CRPEJob::SetNthTableLogOnInfo to set the SQL connection information for the specified table. The propagate flag may be used to cause the change to affect all tables with similar server and database properties.

Syntax
BOOL SetNthTableLogonInfo (

        short tableN,

        const CRPELogOnInfo *logonInfo,

        BOOL propagate );
Parameters

tableN | Specifies the 0-based number of the table for which you want to set logon information.
logonInfo | Specifies a pointer to CRPELogOnInfo.
propagate | Specify TRUE or FALSE to indicate whether the logon information should be used for opening all tables being used in the report.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetNthTablePrivateInfo

Use CRPEJob::SetNthTablePrivateInfo to set database information in CRPETablePrivateInfo.

Syntax
BOOL SetNthTablePrivateInfo (

        short tableN,

        CRPETablePrivateInfo *privateInfo );
Parameters

tableN | Specifies the 0-based number of the table for which you want to set private information.
privateInfo | Specifies a pointer to CRPETablePrivateInfo, which will contain the new information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetNthTableSessionInfo

Use CRPEJob::SetNthTableSessionInfo to set the session information for the specified Microsoft Access table. Many MS Access database tables require that a session be opened before the table can be used. Use this method to open the session.

Syntax
BOOL SetNthTableSessionInfo (

        short tableN,

        const CRPESessionInfo *sessionInfo,

        BOOL propagate );
Parameters

tableN | Specifies the 0-based table number indicating for which MS Access table in the report the session is being opened.
sessionInfo | Specifies a pointer to the structure, CRPESessionInfo.
propagate | Specify TRUE or FALSE to indicate whether the session information should be used for opening all tables being used in the report.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetParameterMinMaxValue

Use CRPEJob::SetParameterMaxMinValue to set the minimum and/or maximum possible values for a specified parameter in a report.

Syntax
BOOL SetParameterMinMaxValue (

            const _TCHAR *parameterFieldName,

            const _TCHAR *reportName,

            CRPEValueInfo *valueMin,

            CRPEValueInfo *valueMax );
Parameters

parameterfieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.
valueMin | Specifies a pointer to CRPEValueInfo, which will contain the minimum value. See Remarks below.
valueMax | Specifies a pointer to CRPEValueInfo, which will contain the maximum value. See Remarks below.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Set valueMin to NULL if specifying maximum value only; valueMin must be non-NULL if valueMax is NULL.
  • Set valueMax to NULL if specifying minimum value only; valueMax must be non-NULL if valueMin is NULL.
  • If both valueMin and valueMax are specified (that is, non-NULL), then the valueType field of both members must be the same or an error code PEP_ERR_INCONSISTANTTYPES will be returned.


CRPEJob::SetParameterPickListOption

Use CRPEJob::SetParameterPickListOption to set the parameter pick list options for a report. This method sets the values in CRPEParameterPickListOption.

Syntax
BOOL SetParameterPickListOption (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        CRPEParameterPickListOption *pickListOption );
Parameters

parameterFieldName | Specifies a pointer to the parameterFieldName for which you want to set pick list options.
reportName | Specifies a pointer to the report name.
pickListOption | Specifies a pointer to CRPEParameterPickListOption, which will contain the new information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob ::SetParameterValueInfo

Use CRPEJob::SetParameterValueInfo to set the information about the values (editable, nullable field, multiple values, etc.) that can be stored in a specified parameter field.

Syntax
BOOL SetParameterValueInfo (

        const _TCHAR *parameterFieldName,

        const _TCHAR *reportName,

        CRPEParameterValueInfo *valueInfo );
Parameters

parameterFieldName | Specifies a pointer to the parameter field name.
reportName | Specifies a pointer to the report name.
valueInfo | Specifies a pointer to CRPEParameterValueInfo, which will contain the new value information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.

CRPEJob::SetPrintDate

Use CRPEJob::SetPrintDate to set only the date that appears in the Print Date Field of the report. This method does not schedule the report to print at a different time or day, but only changes the date that appears in any Print Date Field of the report (for example, use this method to post-date a report when it is printed before the day it is distributed).

Syntax
BOOL SetPrintDate (

        short year,

        short month,

        short day );
Parameters

year | Specifies the year that will appear in the Print Date Field.
month | Specifies the month that will appear in the Print Date Field.
day | Specifies the day that will appear in the Print Date Field.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
CRPEJob::SetPrintOptions

Use CRPEJob::SetPrintOptions to set the print characteristics of a print job. Use this method any time that you want to set the starting page number, the ending page number, the number of report copies, and/or collation instructions in response to user specifications at runtime.

Syntax

BOOL SetPrintOptions ( const CRPEPrintOptions *options );

Parameter

options

Specifies a pointer to CRPEJob::SetPrintOptions, which will contain the information that you want to set.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetReportOptions

Use CRPEJob::SetReportOptions to set the report options associated with a specified print job. This information is specified from the Crystal Reports Designer File | Report Options menu or by CRPEJob::GetReportOptions.

Syntax

BOOL SetReportOptions ( CRPEReportOptions *reportOptions );

Parameter

reportOptions

Specifies a pointer to CRPEReportOptions, which will contain the new report options information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetReportSummaryInfo

Use CRPEJob::SetReportSummaryInfo to set report summary information. Report summary information corresponds to the Summary Info dialog box in Crystal Reports.

Syntax

BOOL SetReportSummaryInfo ( CRPEReportSummaryInfo *summaryInfo );

Parameter

summaryInfo

Specifies a pointer to CRPEReportSummaryInfo, which will contain the new report summary information.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetReportTitle

Use CRPEJob::SetReportTitle to set the report title for the print job. Use this method whenever you need to change the title of a report at print time.

Syntax

BOOL SetReportTitle ( const _TCHAR *title );

Parameter

title

Specifies a pointer to the new title for the report.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetSectionFormat

Use CRPEJob::SetSectionFormat to set the section format settings for selected sections in the specified report to the values in CRPESectionOptions. Use this method to provide specialized formatting for printing invoices, form letters, printing on pre-printed forms, etc.

SetSectionFormat allows you to hide a section, insert a page break either before or after a section begins, reset the page number to 1 after a group value prints, prevent page breaks from spreading data from a single record over two pages, and print group values only at the bottom of a page. For a complete discussion of each of these options, see CRPESectionOptions.

Syntax
BOOL SetSectionFormat (

        short sectionCode,

        const CRPESectionOptions *options );
Parameters

sectionCode | Specifies the code for the report section for which you want to change format information. Use one of the PEP_XXX Section Codes Constants.
options | Specifies a pointer to CRPESectionOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetSectionFormatFormula

Use CRPEJob::SetSectionFormatFormula to change the specified section format formula to the formula string that you supply as a parameter. This method will change only the text of a formula that already exists in the report; you cannot use it to add a formula.

Syntax
BOOL SetSectionFormatFormula (

        short sectionCode,

        short formulaName,

        CString formulaText );
Parameters

sectionCode | Specifies the code for the report section(s) for which you want to set formatting options. See Working with section codes.
formulaName | Specifies the name of the formula for which you want to supply a new string. Use one of the PEP_FFN_XXX Area/Section Format Formula Constants. See Remarks below.
formulaText | The Cstring object that contains the specified formula text when CRPEJob::SetFormula has completed successfully. See Remarks below.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • Returns PEPRR_BADFORMULANAME, if the formula name passed in does not exist, or it does not apply to the section. See Error Codes for further information.
  • Returns PEPERR_BADFORMULATEXT if there is an error in the formula. See Error Codes for further information.
  • When you give the user the ability to change the formula at print time, your link must include code to replace formulaString with a user-generated value.
  • This method should be called before CRPEJob::Start, or the results may be inconsistent or unexpected.
  • Not all formula names can be applied to all sections.


CRPEJob::SetSelectionFormula

Use CRPEJob::SetSelectionFormula to set the formula text for the record selection formula. CRPEJob::SetSelectionFormula is often used with CRPEJob::GetSelectionFormula, to identify and then change an existing selection formula in response to a user selection at print time.

BOOL SetSelectionFormula ( const _TCHAR *formulaText );

Parameter

formulaText

Specifies a pointer to the new selection formula to be assigned to the report.

Returns

TRUE if the call is successful.

  • FALSE if the call fails or if there is an error in the formula.


CRPEJob::SetSectionHeight

Use CRPEJob::SetSectionHeight to set the section height information for the specified section. Use this method whenever you want to specify the section height for printing on pre-printed forms or printing on any other kind of document with a fixed format.

Syntax
BOOL SetSectionHeight (

        short sectionCode,

        short height );
Parameters

sectionCode | Specifies the code for the report sections for which you want to set section height information.
height | Specifies the section height, in twips.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetSQLExpression

Use CRPEJob::SetSQLExpression to enter an SQL expression for the associated print job.

Syntax
BOOL SetSQLExpression (

        const _TCHAR *expressionName,

        const _TCHAR *expressionText );
Parameters

expressionName | Specifies a pointer to the expression name.
expressionText | Specifies a pointer to the SQL expression text.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetSQLQuery

Use CRPEJob::SetSQLQuery to set the SQL query that will be sent to the database server. This method can be used with CRPEJob::GetSQLQuery, to retrieve and then change the SQL query for the report.

Syntax

BOOL SetSQLQuery ( const _TCHAR *query );

Parameter

query

Specifies a pointer to the new SQL query to be sent to the server.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetTrackCursorInfo

Use CRPEJob::SetTrackCursorInfo to set information for tracking the position of the mouse cursor over the preview window. For example, this method can be used to give the user visual feedback, especially when tracking events. CRPEJob::SetTrackCursorInfo is valid only if the report was sent to a preview window and if events for the preview window have been enabled. See CRPEJob::EnableEvent, for more details.

Syntax

BOOL SetTrackCursorInfo ( CRPETrackCursorInfo *cursorInfo );

Parameter

cursorInfo

Specifies a pointer to CRPETrackCursorInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks
  • By default, all area track cursors are arrow cursors.
  • If the preview window contains a drill-down field (database field, summary, group name, group chart), the group area will use a magnify cursor.
  • Group charts in other areas will also use the magnify cursor.


CRPEJob::SetWindowOptions

Use CRPEJob::SetWindowOptions to set the options associated with a specified window object. This information is retrieved from the structure CRPEWindowOptions, by using CRPEJob::GetWindowOptions. Use this method to customize the features of a specified window object.

Syntax

BOOL SetWindowOptions ( const CRPEWindowOptions *windowOptions );

Parameter

windowOptions

Specifies a pointer to CRPEJob::GetWindowOptions, which will contain the information that you want to set.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::Show...Page

Use CRPEJob::Show...Page to display the specified page of a report in the preview window. Use this method to customize how a user moves through pages in a report.

Syntax
BOOL ShowFirstPage ();
BOOL ShowLastPage ();
BOOL ShowNextPage ();
BOOL ShowNthPage ( short pageN );
BOOL ShowPreviousPage ();
Parameter

The following parameter applies only to ShowNthPage.

pageN

Specifies the page number of the report that should be displayed in the preview window.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::ShowPrintControls

Use CRPEJob::ShowPrintControls to specify whether print control buttons are displayed in the preview window. Use this method to display default controls, or to hide default controls and provide customized controls.

Syntax

BOOL ShowPrintControls ( BOOL showControls );

Parameter

showControls

Set to TRUE to indicate that default Print controls are to be displayed in the preview window. Set to FALSE to indicate that no Print controls are to be displayed.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::Start

Use CRPEJob::Start to start the processing of the print job and display the final output of that processing. This is the method that actually prints or exports the report.

Syntax
BOOL Start ();
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SVA2T

Use helper method CRPEJob::SVA2T to convert a ValueInfo structure to UNICODE.

Syntax
void SVA2T (

        CRPEValueInfo *valueOut,

        PEValueInfo *valueIn );
Parameters

Parameter | Description
valueOut | Specifies a pointer to the returned CRPEValueInfo structure, converted to UNICODE.
valueIn | Specifies a pointer to the PEValueInfo input structure.


CRPEJob::SVT2A

Use helper method CRPEJob::SVT2A to convert a ValueInfo structure to ASCII.

Syntax
void SVT2A (

        PEValueInfo *valueOut,

        CRPEValueInfo* valueIn );
Parameters

Parameter | Description
valueOut | Specifies a pointer to the returned PEValueInfo structure, converted to ASCII.
valueIn | Specifies a pointer to the CRPEValueInfo input structure.


CRPEJob::TestNthTableConnectivity

Use CRPEJob::TestNthTableConnectivity to determine whether a valid connection exists to the database for the specified table in the report. This method is typically used if you plan to print at a later time, but you want to test now to confirm that everything is in order for logging on to the database table.

Syntax

BOOL TestNthTableConnectivity ( short tableN );

Parameter

tableN

Specifies the number of the table for which you want to test the connection settings. The first table added to a report is numbered 0, the second is 1, etc.

Returns
  • TRUE if the database session, logon, and location information is all correct.
  • FALSE if the connection fails.


CRPEJob::VerifyDatabase

Use CRPEJob::VerifyDatabase to verify that the database connection(s) specified in a report is (are) valid.

Syntax

BOOL VerifyDatabase ();

Returns
  • TRUE if connection is valid.
  • FALSE if connection is not valid or if call is not successful.


CRPEJob::ZoomPreviewWindow

Use CRPEJob::ZoomPreviewWindow to change the preview window magnification level to the specified level. Use this method when the report has been printed to a preview window and you want to set the magnification of the preview window to a specific level.

Syntax

BOOL ZoomPreviewWindow ( short level );

Parameter

level

Specifies the magnification level to which the preview window is to be zoomed. Use one of the PEP_ZOOM_XXX Zoom Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


class CRPEngine and class CRPEJob Structures

This section describes the structures associated with class CRPEngine and class CRPEJob.

CRPECloseButtonClickedEventInfo

CRPEDrillOnDetailEventInfo

CRPEDrillOnGroupEventInfo

CRPEEnableEventInfo

CRPEExportOptions

CRPEFieldMappingEventInfo

CRPEFieldValueInfo

CRPEFontColorInfo

CRPEFormulaSyntax

CRPEGeneralPrintWindowEventInfo

CRPEGraphAxisInfo

CRPEGraphOptionInfo

CRPEGraphTypeInfo

CRPEGroupOptions

CRPEGroupTreeButtonClickedEventInfo

CRPEHyperlinkEventInfo

CRPEJobInfo

CRPELaunchSeagateAnalysisEventInfo

CRPELogOnInfo

CRPEMouseClickEventInfo

CRPEParameterFieldInfo

CRPEParameterPickListOption

CRPEParameterValueInfo

CRPEPrintOptions

CRPEReadingRecordsEventInfo

CRPEReportFieldMappingInfo

CRPEReportOptions

CRPEReportSummaryInfo

CRPESearchButtonClickedEventInfo

CRPESectionOptions

CRPESessionInfo

CRPEShowGroupEventInfo

CRPEStartEventInfo

CRPEStopEventInfo

CRPESubreportInfo

CRPETableDifferenceInfo

CRPETableLocation

CRPETablePrivateInfo

CRPETableType

CRPETrackCursorInfo

CRPEValueInfo

CRPEWindowOptions

CRPEZoomLevelChangingEventInfo


CRPECloseButtonClickedEventInfo

This structure contains information about a close button-clicked event. When the close button in a preview window is clicked, a callback function will be called with EventId = PEP_CLOSE_BUTTON_CLICKED_EVENT. The fieldValueList will be released after the callback function. Make a copy of the field value list if you want to keep the field value information.

Data Members

The default for each data member is 0.

m_viewIndex | WORD | Specifies which view is going to be closed. Start from 0.
m_windowHandle | long | Specifies on which frame window handle the button is positioned.

Constructor
CRPECloseButtonClickedEventInfo::CRPECloseButtonClickedEventInfo

This constructs a CRPECloseButtonClickedEventInfo structure object. It assigns default values to the members of the structure.

Constructor Syntax

CRPECloseButtonClickedEventInfo ();


CRPEDrillOnDetailEventInfo

This structure provides PEP_DRILL_ON_DETAIL_EVENT event information.

Data Members

Member | Type | Defaul t | Description
m_selectedField Index | short | 0 | A 0-based index indicating which drill-down field was selected. Contains -1 if no field is selected.
m_window Handle | long | 0 | Frame window handle where the drill on detail event happens.
m_fieldValueList | structure | NULL | Specifies a pointer to an array field value of the CRPEFieldValueInfo structure's field value list.
m_nFieldValue | short | 0 | Number of field value in field value of list. For example, if the value is listed second, the number would be 2.

Remarks

If the user clicks one of the fields in the Details section, selectedFieldIndex will point to the field index in fieldValueList. These fields have to be a database field, group name field, summary field, or a formula field. If the user clicks a text object, graph, picture, ole, subreport, special var field, or database memo or blob field, the selectedFieldIndex will return -1.

Constructor
CRPEDrillOnDetailEventInfo::CRPEDrillOnDetailEventInfo

This constructs a CRPEDrillOnDetailEventInfo structure object. It assigns default values to the members of the structure.

Constructor Syntax

CRPEDrillOnDetailEventInfo ();


CRPEDrillOnGroupEventInfo

This structure specifies whether to drill on group information when PEP_DRILL_ON_GROUP_EVENT happens.

Data Members

Member | Type | Default | Description
m_drillType | WORD | 0 | Specifies the type of drill down that is used. Use one of the following PEP_DE_XXX constants.
 | Constant |  | Description
 | PEP_DE_ON_GROUP |  | Drill down on a group summary or subtotal.
 | PEP_DE_ON_GROUPTREE |  | Drill down a Group Tree node.
 | PEP_DE_ON_GRAPH |  | Drill down a group chart object.
 | PEP_DE_ON_MAP |  | Drill down on a map region.
 | PEP_DE_ON_SUBREPORT |  | Drill down on a subreport.
m_windowHandle | long | 0 | Pointer to an array of group names. The list specifies the group path of the selected group. The memory is freed after the callback function is called.
m_groupList | TCHAR | NULL | Specifies a pointer to an array of group names in the report when drilling on a group summary, a Group Tree, a chart, or a map. Specifies a pointer to a single element array containing the subreport name when drilling on a subreport. This memory is freed after the callback function is called.
m_group Level | WORD | 0 | The number of the group name in the group list.

Remarks

The groupList will be freed after the callback function. If you want to keep the groupList, make a copy of it.

Constructor
CRPEDrillOnGroupEventInfo::CRPEDrillOnGroupEventInfo

This constructs a CRPEDrillOnGroupEventInfo structure object. It assigns default values to the members of the structure.

Syntax

CRPEDrillOnGrupEventInfo ();


CRPEEnableEventInfo

This structure specifies which group event is enabled or disabled. All events are disabled by default.

Data Members
  • Each data member is set by the corresponding constructor parameter.
  • Each data member can be set to TRUE, FALSE, or PE_UNCHANGED.
  • The default for each data member is FALSE.

    m_startStopEvent

    short

    Specifies a StartStopEvent.

    m_readingRecordEvent

    short

    Specifies a ReadingRecordEvent.

    m_printWindowButtonEvent

    short

    Specifies a PrintWindowButtonEvent.

    m_drillEvent

    short

    Specifies a DrillEvent.

    m_closePrintWindowEvent

    short

    Specifies a ClosePrintWindowEvent.

    m_activatePrintWindowEvent

    short

    Specifies an ActivatePrintWindowEvent.

    m_fieldMappingEvent

    short

    Specifies a FieldMappingEvent.

    m_mouseClickEvent

    short

    Specifies a MouseClickEvent.

    m_hyperlinkEvent

    short

    Specifies a Hyperlink Event.

    launchSeagateAnalysisEvent

    short

    Specifies a launch Seagate Analysis Event.

    Note: Seagate Analysis is now known as Crystal Analysis.

Remarks

All events are disabled by default. Use CRPEJob::EnableEvent, to enable the desired event.

Constructor CRPEEnableEventInfo::CRPEEnableEventInfo

This constructs a CRPEEnableEventInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEEnableEventInfo ();

Constructor Syntax
CRPEEnableEventInfo (

        short startStopEvent,

        short readingRecordEvent,

        short printWindowButtonEvent,

        short drillEvent,

        short closePrintWindowEvent,

        short activatePrintWindowEvent,

        short fieldMappingEvent,

        short mouseClickEvent,

        short hyperlinkEvent,

        short launchSeagateAnalysisEvent );


CRPEExportOptions

This structure is used to retrieve and set the export options of a print job. It is used by member function CRPEJob::ExportTo.

Data Members

Each data member is set by the corresponding constructor parameter.

Member | Type | Default | Description
m_formatDLLName | _TCHAR | '\0' | Specifies the name of the format DLL (of length PEP_DLL_NAME_LEN = 64) that contains the export format to be used. Select a DLL from the Export Format DLL table below.
m_formatType | DWORD | 0 | Specifies the export format to be used. Select a DLL from the Export Format Type table below.
m_formatOptions | void | NULL | Specifies additional export information specific to the format type being used. This parameter is required for certain format types only. If you assign the default NULL to formatOptions, the Crystal Report Engine will automatically prompt the user for format information if it is needed. Alternatively, you can choose one from the Export Format Options table below.
m_destinationDLLName | _TCHAR | '\0' | Specifies the name of the destination DLL (of length PEP_DLL_NAME_LEN = 64) that contains the destination type to be used. Select a destination DLL from the Destination DLL Name table below.
m_destinationType | DWORD | 0 | Specifies the destination type of the exported report. Select a destination type from the Destination Type table below.
m_destinationOptions | void | NULL | Provides additional information specific to the export destination type. If you assign the default NULL to destinationOptions, the Crystal Report Engine will automatically prompt the user for destination information if it is needed. Alternatively, you can choose one from the Export Destination Options Type table below.
m_nFormatOptionsBytes | WORD | 0 | Automatically assigned by CRPEJob::GetExportOptions. Unused by CRPEJob::ExportTo.
m_nDestinationOptions Bytes | WORD | 0 | Automatically assigned by CRPEJob::GetExportOptions. Unused by CRPEJob::ExportTo.


CRPEExportOptions Options Tables
Export Format DLL

Export Format | DLL
Crystal Reports Format | uxfcr.dll
Data Interchange Format | uxfdif.dll
Word for Windows Format | uxfwordw.dll
Word for DOS Format | uxfdoc.dll
WordPerfect Format | uxfdoc.dll
Quattro Pro 5.0 (WB1) Format | uxfqp.dll
Record Style Format (columns) | uxfrec.dll
Rich Text Format | uxfrtf.dll
Comma Separated Values (CSV) | uxfsepv.dll
Tab Separated Values | uxfsepv.dll
Character Separated Values | uxfsepv.dll
Text Format (ASCII) | uxftext.dll
Tab Separated Text Format | uxftext.dll
Lotus 1-2-3 (WK3) | uxfwks.dll
Excel 4.0 | uxfxls.dll

Export Format Type

Export Format | Format Type
Crystal Reports Format | UXFCrystalReportType
Data Interchange Format | UXFDIFType
Word for Windows Format | UXFWordWinType
Word for DOS Format | UXFWordDosType
WordPerfect Format | UXFWordPerfectType
Quattro Pro 5.0 (WB1) Format | UXFQP5Type
Record Style Format (columns) | UXFRecordType
Rich Text Format | UXFRichTextFormatType
Comma Separated Values (CSV) | UXFCommaSeparatedType
Tab Separated Values | UXFTabSeparatedType
Character Separated Values | UXFCharSeparatedType
Text Format (ASCII) | UXFTextType
Tab Separated Text Format | UXFTabbedTextType
Lotus 1-2-3 (WK3) | UXFLotusWk3Type
Excel 4.0 | UXFXls4Type

Export Format Options

Export Format | Format Type
Data Interchange Format | UXFDIFOptions
Record Style Format (columns) | UXFRecordStyleOptions
Comma Separated Values (CSV) | UXFCommaTabSeparatedOptions
Tab Separated Values | UXFCommaTabSeparatedOptions
Character Separated Values | UXFCharSeparatedOptions

Destination DLL Name

Report Destination | DLL
Disk File | uxddisk.dll
E-mail (MAPI) | uxdmapi.dll
E-mail (VIM) | uxdvim.dll

Destination Type

Report Destination | Destination Type
Disk File | UXDDiskType
E-mail (MAPI) | UXDMapiType
E-mail (VIM) | UXDVIMType

Export Destination Options Type

Report Destination | Structure
Disk File | UXDDiskOptions
E-mail (MAPI) | UXDMAPIOptions
E-mail (VIM) | UXDVIMOptions

Constructor CRPEExportOptions::CRPEExportOptions

This constructs a CRPEExportOptions structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

struct CRPEExportOptions ();

Constructor Syntax
struct CRPEExportOptions (

        const _TCHAR *formatDLLName,

        DWORD formatType,

        void *formatOptions,

        const _TCHAR *destinationDLLName,

        DWORD destinationType,

        void *destinationOptions );


CRPEFieldMappingEventInfo

This structure provides field mapping event information.

Data Members

Each data member is set by the corresponding constructor parameter.

Member | Type | Default | Description
m_reportFields | WORD | NULL | An array of fields in the report. See Remarks below.
m_nReportFields | WORD | 0 | The size of the reportFields array.
m_databaseFields | WORD | NULL | An array of fields in the new database. See Remarks below.
m_nDatabaseFields | WORD | 0 | The size of the databaseFields array.

Remarks
  • Member reportFields is an array of fields in the report of size nReportFields. The user must modify the 'mappingTo' of each newly mapped field by assigning the value of the index of a field in the array databaseFields.
  • Member databaseFields is an array of fields in the new database file of size nDatabaseFields.
  • CRPEReportFieldMappingInfo.mappingTo must be modified for each newly mapped field by assigning the value of the index of a field in the databaseFields array.
Constructor CRPEFieldMappingEventInfo::CRPEFieldMappingEventInfo

This constructs a CRPEFieldMappingEventInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEFieldMappingEventInfo ();

Constructor Syntax
CRPEFieldMappingEventInfo (

        CRPEReportFieldMappingInfo *reportFields,

        WORD nReportFields,

        CRPEReportFieldMappingInfo *databaseFields,

        WORD nDatabaseFields );


CRPEFieldValueInfo

This structure specifies a field value in the fieldValueList of the structure CRPEDrillOnDetailEventInfo.

Data Members

Member | Type | Default | Description
m_ignored | WORD | 0 | For 4 byte alignment. Ignore.
m_fieldName | _TCHAR | '\0' | Specifies the field name (of length PEP_FIELD_NAME_LEN = 512).
m_fieldValue | CRPEValueInfo | CRPEValueInfo() | CRPEValueInfo's field value for the selected Details area specified by the fieldName member variable.

Remarks

A selected Details area corresponds to a database record.

Constructor CRPEFieldValueInfo::CRPEFieldValueInfo

This constructs a CRPEFieldValueInfo structure object. It assigns default values to the members of the structure.

Constructor Syntax

CRPEFieldValueInfo ();


CRPEFontColorInfo

CRPEFontColorInfo contains information regarding the fonts used in a chart.

Data Members
  • Each data member is set by the corresponding constructor parameter.
  • The default value for each data member is 0, except for m_faceName and m_color.

    Member Type Description

    m_faceName

    _TCHAR

    Specifies the font face name (of length PEP_FACE_NAME_LEN = 64). Use an empty string ("") for no change. Default is '\0'.

    m_fontFamily

    short

    Specifies the font family. Use FF_DONTCARE for no change.

    m_fontPitch

    short

    Specifies the font pitch. Use DEFAULT_PITCH for no change.

    m_charSet

    short

    Specifies the font charset. Use DEFAULT_CHARSET for no change.

    m_pointSize

    short

    Specifies the desired point size for the selected font. Use this member or member twipSize to specify the font size. If both members are non-zero, then this member will be ignored and twipSize will be used. Pass 0 for both twipSize and pointSize for no change.

    m_isItalic

    short

    Boolean. If TRUE, the text is italic. Use PEP_UNCHANGED for no change.

    m_isUnderlined

    short

    Boolean. If TRUE, the text is underlined. Use PEP_UNCHANGED for no change.

    m_isStruckOut

    short

    Boolean. If TRUE, the text is struckout. Use PEP_UNCHANGED for no change.

    m_weight

    short

    Specifies the font weight. Use 0 for no change.

    m_color

    COLORREF

    Specifies Windows COLORREF or PEP_UNCHANGED_COLOR or no change. Default is PEP_UNCHANGED_COLOR.

    m_twipSize

    short

    Specifies the font size, in twips. Use this member or member pointSize to specify the font size. If both members are non-zero, then this member will be used and pointSize will be ignored. Pass 0 for both twipSize and pointSize for no change.

Constructor CRPEFontColorInfo::CRPEFontColorInfo

This constructs a CRPEFontColorInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEFontColorInfo ()

Constructor Syntax
CRPEFontColorInfo (

        const _TCHAR *faceName,

        short fontFamily,

        short fontPitch,

        short charSet,

        short pointSize,

        short isItalic,

        short isUnderlined,

        short isStruckOut,

        short weight,

        COLORREF color

        short twipSize );

CRPEFormulaSyntax

CRPEFormulaSyntax contains information related to the syntax of the specified formula.

Data Members
  • Each data member is set by the corresponding constructor parameter.
  • The default for each member of the m_formula syntax array is 0 (PEP_FST_CRYSTAL).

    Member Type Description

    m_formulaSyntax

    short

    Specifies an array (of size PEP_FS_SIZE = 2) which contains the formula syntax information as PEP_FST_XXX Formula Syntax Constants constants or PEP_UNCHANGED for no change.

Constructor CRPEFormulaSyntax::CRPEFormulaSyntax

This constructs a CRPEFormulaSyntax structure object. It assigns default values to the members of the structure.

Constructor Syntax (Default)

CRPEFormulaSyntax ()


CRPEGeneralPrintWindowEventInfo

This structure specifies general preview window event information and is used for the following events.

  • PRINT_WINDOW_EVENT
  • PEP_CLOSE_PEP_PRINT_BUTTON_CLICKED_EVENT
  • PEP_EXPORT_BUTTON_CLICKED_EVENT
  • PEP_FIRST_PAGE_BUTTON_CLICKED_EVENT
  • PEP_PREVIOUS_PAGE_BUTTON_CLICKED_EVENT
  • PEP_NEXT_PAGE_BUTTON_CLICKED_EVENT
  • PEP_LAST_PAGE_BUTTON_CLICKED_EVENT
  • PEP_CANCEL_BUTTON_CLICKED_EVENT
  • PEP_PRINT_SETUP_BUTTON_CLICKED_EVENT
  • PEP_REFRESH_BUTTON_CLICKED_EVENT
  • PEP_ACTIVATE_PRINT_WINDOW_EVENT
  • PEP_DEACTIVATE_PRINT_WINDOW_EVENT
Data Members

The default for each data member is 0.

m_ignored | WORD | For 4 byte alignment. Ignore.
m_windowHandle | long | Frame window handle where the event happens.

Constructor
CRPEGeneralPrintWindowEventInfo::CRPEGeneralPrintWindowEventInfo

This constructs a CRPEGeneralPrintWindowEventInfo structure object.

Constructor Syntax (Default)
CRPEGeneralPrintWindowEventInfo ();


CRPEGraphAxisInfo

The CRPEGraphAxisInfo structure contains information about how the axis of a chart are calculated and displayed.

Data Members

Each data member is set by the corresponding constructor parameter.

The default value for each data member is 0.

Member | Type | Description
m_groupAxisGridLine | short | Specifies how gridlines are displayed on the chart. Use one of the PEP_GGT_XXX Graph Gridline Constants, or PEP_UNCHANGED for no change.
m_dataAxisYGridLine | short | Specifies how gridlines are displayed on the chart. Use one of the PEP_GGT_XXX Graph Gridline Constants, or PEP_UNCHANGED for no change.
m_dataAxisY2GridLine | short | Specifies how gridlines are displayed on the chart. Use one of the PEP_GGT_XXX Graph Gridline Constants, or PEP_UNCHANGED for no change.
m_seriesAxisGridline | short | Specifies how gridlines are displayed on the chart. Use one of the PEP_GGT_XXX Graph Gridline Constants, or PEP_UNCHANGED for no change.
m_dataAxisYMinValue | double | Specifies the minimum value for the axis.
m_dataAxisYMaxValue | double | Specifies the maximum value for the axis.
m_dataAxisY2MinValue | double | Specifies the minimum value for the axis.
m_dataAxisY2MaxValue | double | Specifies the maximum value for the axis.
m_seriesAxisMinValue | double | Specifies the minimum value for the axis.
m_seriesAxisMaxValue | double | Specifies the maximum value for the axis.
m_dataAxisYNumber Format | short | Specifies the format for the display of numeric values on the chart. Use one of the PEP_GNF_XXX Chart Number Format Constants, or PEP_UNCHANGED for no change.
m_dataAxisY2Number Format | short | Specifies the format for the display of numeric values on the chart. Use one of the PEP_GNF_XXX Chart Number Format Constants, or PEP_UNCHANGED for no change.
m_seriesAxisNumber Format | short | Specifies the format for the display of numeric values on the chart. Use one of the PEP_GNF_XXX Chart Number Format Constants, or PEP_UNCHANGED for no change.
m_dataAxisYAutoRange | short | Boolean, or PEP_UNCHANGED for no change. If TRUE, the axis will autorange.
m_dataAxisY2AutoRange | short | Boolean, or PEP_UNCHANGED for no change. If TRUE, the axis will autorange.
m_seriesAxisAutoRange | short | Boolean, or PEP_UNCHANGED for no change. If TRUE, the axis will autorange.
m_dataAxisY AutomaticDivision | short | Use one of the PEP_ADM_XXX Graph Axis Division Method Constants, or PEP_UNCHANGED for no change.
m_dataAxisY2 AutomaticDivision | short | Use one of the PEP_ADM_XXX Graph Axis Division Method Constants, or PEP_UNCHANGED for no change.
m_seriesAxis AutomaticDivision | short | Use one of the PEP_ADM_XXX Graph Axis Division Method Constants, or PEP_UNCHANGED for no change.
m_dataAxisYManual Division | long | Valid only if the corresponding axis m_dataAxisYAutomaticDivision is FALSE.
m_dataAxisY2Manual Division | long | Valid only if the corresponding axis m_dataAxisY2AutomaticDivision is FALSE.
m_seriesAxisManual Division | long | Valid only if the corresponding axis m_seriesAxisAutomaticDivision is FALSE.
m_dataAxisYAutoScale | short | Boolean, or PEP_UNCHANGED for no change. Specifies whether the axis should autoscale.
m_dataAxisY2AutoScale | short | Boolean, or PEP_UNCHANGED for no change. Specifies whether the axis should autoscale.
m_seriesAxisAutoScale | short | Boolean, or PEP_UNCHANGED for no change. Specifies whether the axis should autoscale.

Constructor CRPEGraphAxisInfo::CRPEGraphAxisInfo

This constructs a CRPEGraphAxisInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEGraphAxisInfo ()

Constructor Syntax
CRPEGraphAxisInfo (

        WORD StructSize,

        short groupAxisGridLine,

        short dataAxisYGridLine,

        short dataAxisY2GridLine,

        short seriesAxisGridline,

        double dataAxisYMinValue,

        double dataAxisYMaxValue,

        double dataAxisY2MinValue,

        double dataAxisY2MaxValue,

        double seriesAxisMinValue,

        double seriesAxisMaxValue,

        short dataAxisYNumberFormat,

        short dataAxisY2NumberFormat,

        short seriesAxisNumberFormat,

        short dataAxisYAutoRange,

        short dataAxisY2AutoRange,

        short seriesAxisAutoRange,

        short dataAxisYAutomaticDivision,

        short dataAxisY2AutomaticDivision,

        short seriesAxisAutomaticDivision,

        long dataAxisYManualDivision,

        long dataAxisY2ManualDivision,

        long seriesAxisManualDivision,

        short dataAxisYAutoScale,

        short dataAxisY2AutoScale,

        short seriesAxisAutoScale );


CRPEGraphOptionInfo

The CRPEGraphOptionInfo structure contains information on several options available with charts.

Data Members
  • Each data member is set by the corresponding constructor parameter.
  • The default for each data member is 0.
  • For each data member, use PEP_UNCHANGED for no change.

    Member Type Description

    m_graphColour

    short

    Specifies the chart color. Use one of thePEP_GCR_XXX Graph Color Constants.

    m_showLegend

    short

    Boolean. If TRUE, the chart legend will be visible. If FALSE, the chart legend will be hidden.

    m_legendPosition

    short

    Specifies the position of the legend on the chart if m_showLegend is TRUE. Use one of the PEP_GLP_XXX Graph Placement Constants.

    m_pieSize

    short

    Specifies the size of the slice on a pie or a doughnut chart. Use one of the PEP_GPS_XXX Graph Pie Size Constants.

    m_detachedPieSlice

    short

    Specifies the detachment of the slice on a pie or doughnut chart. Use one of the PEP_GDPS_XXX Graph Detached Pie Slice Constants.

    m_barSize

    short

    Specifies the bar size on bar charts. Use one of the PEP_GBS_XXX Graph Bar Size Constants.

    m_verticalBars

    short

    Boolean. If TRUE, there will be vertical bars on bar charts.

    m_markerSize

    short

    Specifies the size of the marker on line and bar charts. Use one of the PEP_GMS_XXX Graph Marker Size Constants.

    m_markerShape

    short

    Specifies the shape of the marker on line and bar charts. USe one of the PEP_GMSP_XXX Graph Marker Shape Constants.

    m_dataPoints

    short

    Specifies how data points will be shown. Use one of the PEP_GDP_XXX Chart Data Point Constants.

    m_dataValueNumber
    Format

    short

    Specifies the number format for values on the chart. Use one of the PEP_GNF_XXX Chart Number Format Constants.

    m_viewingAngle

    short

    Specifies the viewing angle with which a 3D chart will be shown. Use one of the PEP_GVA_XXX Graph Viewing Angle Constants.

    m_legendLayout

    short

    Specifies the chart legend layout. Use one of the PEP_GLL_XXX Graph Legend Layout Constants. Default = PEP_GLL_PERCENTAGE.

Constructor CRPEGraphOptionInfo::CRPEGraphOptionInfo

This constructs a CRPEGraphOptionInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEGraphOptionInfo ();

Constructor Syntax
CRPEGraphOptionInfo (

        short graphColour,

        short showLegend,

        short legendPosition,

        short pieSize,

        short detachedPieSlice,

        short barSize,

        short verticalBars,

        short markerSize,

        short markerShape,

        short dataPoints,

        short dataValueNumberFormat,

        short viewingAngle,

        short legendLayout )


CRPEGraphTypeInfo

The CRPEGraphTypeInfo structure contains information on what chart type is specified.

Data Members
  • Each data member is set by the corresponding constructor parameter.
  • The default for each member is 0.

    m_graphType

    short

    Specifies the chart type. Uses one of the PEP_GT_XXX Graph Type and Subtype Constants, or PEP_UNCHANGED for no change.

    m_graphSubtype

    short

    Specifies the chart subtype. Uses one of the PEP_GST_XXX Graph Type and Subtype Constants, or PEP_UNCHANGED for no change.

Constructor CRPEGraphTypeInfo::CRPEGraphTypeInfo

This constructs a CRPEGraphTypeInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEGraphTypeInfo ();

Constructor Syntax
CRPEGraphTypeInfo (

        short graphType,

        short graphSubtype );


CRPEGroupOptions

This structure contains information about several options available with report groups. This information is used by CRPEJob::GetGroupOptions, to retrieve current options and by CRPEJob::SetGroupOptions, to pass new option settings.

Data Members

Each data member is set by the corresponding constructor parameter.

Member | Type | Default | Description
m_condition | short | 0 | Specifies the condition setting for the selected group section. See Remarks below.
m_fieldName | _TCHAR | '\0' | Specifies the field name of the group field (of size PEP_FIELD_NAME_LEN = 512), or remains empty for no change.
m_sortDirection | short | 0 Descending | Specifies the sort direction. Uses one of the PEP_SF_XXX Sort Order Constants or PEP_UNCHANGED for no change. For group conditions only, use PEP_SF_ORIGINAL for original order or PEP_SF_SPECIFIED for read-only specified sort order.
m_repeatGroup Header | short | 0 | BOOL value, or PEP_UNCHANGED for no change.
m_keepGroup Together | short | 0 | BOOL value, or PEP_UNCHANGED for no change.
m_topOrBottom NGroups | short | 0 | Use one of the following PEP_GO_TBN_XXX constants or PEP_UNCHANGED for no change.
 | Constant |  | Description
 | PEP_GO_TBN_ALL_ GROUPS_UNSORTED |  | There is no group sorting or Top/Bottom N for this level of grouping.
 | PEP_GO_TBN_ALL_ GROUPS_SORTED |  | There is group sorting, but not Top/Bottom N.
 | PEP_GO_TBN_TOP_ N_GROUPS |  | Top N groups will be selected.
 | PEP_GO_TBN_ BOTTOM_N_GROUPS |  | Bottom N groups will be selected.
Member | Type | Default | Description
m_topOrBottom NSortFieldName | _TCHAR | '\0' | Specifies the name of the summary field (of size PEP_FIELD_NAME_LEN = 512) by which the groups are ordered, or remains empty for no change.
m_nTopOr BottomGroups | short | 0 Keep all groups | Number of groups to select.
m_discardOther Groups | short | 0 | Determines whether the remaining groups are collected into an Others group or discarded. BOOL value, or PEP_UNCHANGED for no change.
hierarchical Sorting | short | FALSE | Boolean. Specifies whether or not to do hierarchial sorting.
*instanceIDField | _TCHAR | '\0' | Specifies a pointer to the name of the instance ID field (of size PEP_FIELD_NAME_LEN = 512) for hierarchial sorting.
*parentIDField | _TCHAR | '\0' | Specifies a pointer to the name of the parent ID field (of size PEP_FIELD_NAME_LEN = 512) for hierarchial sorting.
groupIndent | long | 0 | Specifies the indent for the group, in twips.

Remarks
  • For data member m_condition, use PEP_GC_TYPEMASK and PEP_GC_CONDITIONMASK for decoding the group condition and a PEP_GC_XXX constant or PEP_UNCHANGED for setting the group condition.
  • If topOrBottomNGroups is PEP_GO_TBN_TOP_N_GROUPS or PEP_GO_TBN_BOTTOM_N_GROUPS, all the group sort fields related to this group will be deleted. A new group sort field will be added with the sort direction of descending or ascending. The group sort field will be sorted by specifying topOrBottomNSortFieldName if it is not empty. It will be sorted by the first group sort field name related to this group (before it is deleted) if topOrBottomNSortFieldName is empty.
Constructor CRPEGroupOptions::CRPEGroupOptions

This constructs a CRPEGroupOptions structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEGroupOptions ();

Constructor. Syntax
CRPEGroupOptions (

        short condition,

        _TCHAR *fieldName,

        short  sortDirection,

        short  repeatGroupHeader,

        short  keepGroupTogether,

        short  topOrBottomNGroups,

        _TCHAR *topOrBottomNSortFieldName,

        short  nTopOrBottomGroups,

        short  discardOtherGroups,

        short  hierarchicalSorting

        _TCHAR instanceIDField

        _TCHAR parentIDField

        long   groupIndent );


CRPEGroupTreeButtonClickedEventInfo

This structure provides information about the group tree button clicked event, when the callback function is called with the event ID equal to PEP_GROUP_TREE_BUTTON_CLICKED_EVENT.

Data Members

Member | Type | Default | Description
m_visible | short | FALSE | Indicates whether the group tree is shown or hidden.
m_windowHandle | long | 0 | Frame window handle where the event happens.

Constructor
CRPEGroupTreeButtonEventInfo ::CRPEGroupTreeButtonClickedEventInfo

This constructs a CRPEGroupTreeButtonClickedEventInfo structure object. It assigns default values to the members of the structure.

Constructor Syntax

CRPEGroupTreeButtonClickedEventInfo ();


CRPEHyperlinkEventInfo

This structure provides information about a selected hyperlink.

Data Members

Member | Type | Default | Description
m_ignored | WORD | 0 | For 4 byte alignment. Ignore.
m_windowHandle | long | 0 | HWND specifies the handle of the window where the event happened.
m_hyperlinkText | _TCHAR | '\0' | Specifies a pointer to the hyperlink text (of length PEP_HYPERLINK_LEN= 256) associated with the object. The memory pointed to by hyperlinkText is freed after calling the callback function.

Constructor CRPEHyperlinkEventInfo::CRPEHyperlinkEventInfo

This constructs a CRPEHyperlinkEventInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEHyperlinkEventInfo ();

Constructor Syntax
CRPEHyperlinkEventInfo (

        long windowHandle,

        _TCHAR *hyperlinkText );


CRPEJobInfo

This structure is used by CRPEJob::GetJobStatus. Status information concerning the job is returned through this structure.

Data Members

Member | Type | Default | Description
m_numRecordsRead | DWORD | 0 | Specifies the number of records actually processed.
m_numRecords Selected | DWORD | 0 | Specifies the number of records selected for inclusion in the report out of the total number of records read.
m_numRecords Printed | DWORD | 0 | Specifies the number of records actually printed.
m_displayPageN | WORD | 0 | Specifies the page number of the currently displayed page in the preview window.
m_latestPageN | WORD | 0 | Specifies the number of the last page that is currently available. Once the printing is complete, this value is the number of the last page.
m_startPageN | WORD | 0 | Specifies the number of the starting page.
m_printEnded | BOOL | FALSE | Specifies whether the printing process is completed.

Constructor CRPEJobInfo::CRPEJobInfo

This constructs a CRPEJobInfo structure object. It assigns default values to the members of the structure.

Constructor Syntax (Default)

CRPEJobInfo ();


CRPELaunchSeagateAnalysisEventInfo

This structure provides information about a Launch Seagate Analysis Event.

Note: Seagate Analysis is now known as Crystal Analysis.

Data Members

Member | Type | Default | Description
m_ignored | WORD | 0 | For 4 byte alignment. Ignore.
m_windowHandle | long | 0 | HWND specifies the handle of the window where the event happened.
m_pathFile | _TCHAR | '\0' | Specifies a pointer to the path and filename (of length PEP_PATHFILE_LEN = 256) of the temporary report. The memory pointed to by pathFile is freed after calling the callback function.

Constructor CRPELaunchSeagateAnalysisEventInfo::CRPELaunchSeagateAnalysisEventInfo

This constructs a CRPELaunchSeagateAnalysisEventInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPELaunchSeagateAnalysisEventInfo ();

Constructor Syntax
CRPELaunchSeagateAnalysisEventInfo (

        long windowHandle,

        _TCHAR *pathFile );


CRPELogOnInfo

This structure contains SQL connection information and is used by the following member functions.

  • CRPEngine::LogOnServer
  • CRPEngine::LogOffServer
  • CRPEJob::GetNthTableLogOnInfo
  • CRPEJob::SetNthTableLogOnInfo
Data Members
  • Each data member is set by the corresponding constructor parameter.
  • Specify an empty string ("") to use the value already set in the report.
  • Specify a non-empty string (for example, "Server A") to override a value in the report.
  • All strings are null-terminated.
  • The default for each data member is '\0'.
  • For Netware SQL, pass the dictionary path name in serverName and the data path name in databaseName.

    m_serverName

    _TCHAR

    Specifies the logon name (of length PEP_SERVERNAME_LEN = 128) for the server used to create the report.

    m_database
    Name

    _TCHAR

    Specifies the logon name (of length PEP_DATABASENAME_LEN = 128) for the database used to create the report.

    m_userID

    _TCHAR

    Specifies the user ID (of length PEP_USERID_LEN = 128) necessary to log on to the server.

    m_password

    _TCHAR

    Specifies the password (of length PEP_PASSWORD_LEN = 128) necessary to log on to the server. Password is undefined when getting information from the report.

Constructor CRPELogOnInfo::CRPELogOnInfo

This constructs a CRPELogOnInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPELogOnInfo ();

Constructor Syntax
CRPELogOnInfo (

        const _TCHAR *serverName,

        const _TCHAR *databaseName,

        const _TCHAR *userID,

        const _TCHAR *password );


CRPEMouseClickEventInfo

The CRPEMouseClickEventInfo structure contains information related to mouse click events.

Data Members

Each data member is set by the corresponding constructor parameter.

Member | Type | Default | Description
m_windowHandle | long | 0 | windowHandle.
m_clickAction | UNIT | 0 | The click action, button down or up.
m_clickFlags | UNIT | 0 | Any combination of one or more of the following mouse click flag (virtual key state-masks) constants.
 | Constant | Value | Description
 | PEP_CF_NONE | 0x0000 | No button clicked.
 | PEP_CF_LBUTTON | 0x0001 | Left mouse button clicked.
 | PEP_CF_RBUTTON | 0x0002 | Right mouse button clicked.
 | PEP_CF_SHIFTKEY | 0x0004 | Shift key depressed.
 | PEP_CF_CONTROLKEY | 0x0008 | Control key depressed.
 | PEP_CF_MBUTTON | 0x0010 | Middle mouse button clicked.
Member | Type | Default | Description
m_xOffset | int | 0 | The x-coordinate of the mouse click in pixels.
m_yOffset | int | 0 | The y-coordinate of the mouse click in pixels.
m_fieldValue | CRPEValueInfo | NULL | Specifies the CRPEValueInfo structure containing the value of the object at the click point. See Remarks below.
m_objectHandle | DWORD | 0 | Design view object handle.
m_sectionCode | short | 0 | The code for the section in which the click occurred.

Remarks

Member fieldValue represents a pointer to a CRPRValueInfo structure containing the value of the object at the click point if it is a field object (excluding MEMO and BLOB fields); otherwise valueType element = PEP_VI_NOVALUE.

Constructor CRPEMouseClickEventInfo::CRPEMouseClickEventInfo

This constructs a CRPEMouseClickEventInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEMouseClickEventInfo ();

Constructor Syntax
CRPEMouseClickEventInfo (

        long windowHandle,

        UINT clickAction,

        UINT clickFlags,

        int xOffset,

        int yOffset,

        CRPEValueInfo *fieldValue,

        DWORD objectHandle,

        short sectionCode );


CRPEParameterFieldInfo

The CRPEParameterFieldInfo structure contains information related to parameter fields in a report. This structure is used by CRPEJob::GetNthParameterField, to get information about a specific parameter field and by CRPEJob::SetNthParameterField, to change a specific parameter field.

Data Members
  • Each data member is set by the corresponding constructor parameter except as noted below.
  • If you wish to set a parameter to NULL, set the CurrentValue to CRWNULL. CRWULL is of Type String and is independent of the data type of the parameter.

    Member | Type | Default | Description

    m_Value
    Type

    WORD

    0

    Specifies the data type of the parameter field. The Crystal Report Engine supports the following data types and associated PEP_PF_XXX constants.

             Data Type Constant

    Number

    PEP_PF_NUMBER

    Currency

    PEP_PF_CURRENCY

    Boolean

    PEP_PF_BOOLEAN

    Date

    PEP_PF_DATE

    String

    PEP_PF_STRING

    Date/Time

    PEP_PF_DATETIME

    Time

    PEP_PF_TIME

    Member | Type | Default | Description

    m_Default
    ValueSet

    WORD

    0

    Specifies whether a default value is set for the parameter field. The value can be either TRUE if you want to change the default value or FALSE if you do not.

    m_Current
    ValueSet

    WORD

    0

    Indicates whether a new value is being assigned to the parameter field. Use TRUE to indicate that a new value is set, FALSE to indicate no change.

    m_Name

    _TCHAR

    '\0'

    Specifies the name of the parameter field (of length PEP_PF_NAME_LEN = 256, NULL-terminated) to be assigned a new value.

    m_Prompt

    _TCHAR

    '\0'

    Specifies the prompting text (of length PEP_PF_PROMPT_LEN = 256, NULL-terminated), if any, that will appear when the user runs the report for the first time or refreshes the data.

    m_Default
    Value

    _TCHAR

    '\0'

    Specifies the default value assigned to the parameter field. If the DefaultValueSet member is FALSE, this value is meaningless. DefaultValue can be a Number, Date, DateTime, Time, Boolean, or String (of length PEP_PF_VALUE_LEN = 256).

    m_Current
    Value

    _TCHAR

    '\0'

    Specifies the current value assigned to the parameter field. If CurrentValueSet is FALSE, this value is meaningless. CurrentValue can be a Number, Date, DateTime, Time, Boolean, or String (of length PEP_PF_VALUE_LEN = 256).

    m_Report
    Name

    TCHAR

    '\0'

    The name of the report where the field belongs (used only with CRPEJob::GetNthParameterField, and NewParameterField; set only by the default constructor).

    m_needs
    CurrentValue

    WORD

    0

    Returns FALSE if the parameter is linked, not in use, or has current value set (set only by the default constructor).

    m_isLimited

    WORD

    0

    Specifies whether or not the parameter field is limited in length (Strings) or by a range (other data types).

    m_MinSize

    double

    0

    Depending on the value type, sets the minimum length of the string or minimum numeric value.

    m_MaxSize

    double

    0

    Depending on the value type, sets the maximum length of the string or maximum numeric value.

    m_EditMask

    _TCHAR

    \0'

    An edit mask (of length PEP_PF_EDITMASK_LEN = 256) that restricts what may be entered for string parameters.

    m_isHidden

    WORD

    FALSE

    TRUE if an essbase sub var.

Constructor CRPEParameterFieldInfo::CRPEParameterFieldInfo

This constructs a CRPEParameterFieldInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEParameterFieldInfo ();

Constructor Syntax
CRPEParameterFieldInfo (

        WORD ValueType,

        WORD DefaultValueSet,

        WORD CurrentValueSet,

        const _TCHAR *Name,

        const _TCHAR *Prompt,

        const _TCHAR *DefaultValue,

        const _TCHAR *CurrentValue,

        WORD isLimited,

        double MinSize,

        double MaxSize,

        const _TCHAR *EditMask,

        WORD isHidden );


CRPEParameterPickListOption

CRPEParameterPickListOption structure contains information related to parameter sort methods.

Data Members
  • Each data member is set by the corresponding constructor parameter.
  • The default value for each data member is 0.

    Member Type Description

    m_showDescOnly

    short

    Boolean, or PEP_UNCHANGED for no change.

    m_sortMethod

    short

    Specifies the sort method. Use one of the PEP_OR_XXX Sort Method Constants, or PEP_UNCHANGED for no change.

    m_sortBasedOnDesc

    short

    Boolean, or PEP_UNCHANGED for no change.

Constructor CRPEParameterPickListOption::CRPEParameterPickListOption

This constructs a CRPEParameterPickListOption structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEParameterPickListOption ()

Constructor Syntax
CRPEParameterPickListOption (

        WORD  StructSize,

        short showDescOnly,

        short sortMethod,

        short sortBasedOnDesc );


CRPEParameterValueInfo

The CRPEParameterValueInfo structure contains information related to parameter values in a report. This structure is used with the method CRPEJob::GetParameterValueInfo, and CRPEJob ::SetParameterValueInfo, to set specific parameter value information.

Data Members
  • Each data member is set by the corresponding constructor parameter.
  • The default value for each data member is PEP_UNCHANGED.

    m_isNullable

    short

    Specifies whether or not a field is nullable in a report. Set this variable to TRUE if you want a nullable report field, FALSE if you do not, or PEP_UNCHANGED to keep the existing setting.

    m_disallowEditing

    short

    Specifies whether or not a report field can be edited. Set this variable to TRUE if you want to disallow report field editing, FALSE if you do not, or PEP_UNCHANGED to keep the existing setting.

    m_allowMultiple
    Values

    short

    Specifies whether or not a field can have multiple values in a report. Set this variable to TRUE if you want to allow multiple values in a report field, FALSE if you do not, or PEP_UNCHANGED to keep the existing setting.

    m_hasDiscreteValues

    short

    Specifies whether or not a field has discrete values in a report. Uses one of the following PEP_DR_XXX constants, or PEP_UNCHANGED to keep existing setting.

            Constant

    PEP_DR_HASRANGE

    PEP_DR_HASDISCRETE

    PEP_DR_HASDISCRETEANDRANGE

    m_partOfGroup

    short

    Specifies whether or not the parameter field is a member of a group. Set this variable to TRUE if a report field is part of a group, FALSE if not, or PEP_UNCHANGED to keep the existing setting.

    m_groupNum

    short

    Specifies the group number or PEP_UNCHANGED to keep the existing group number.

    m_mutuallyExclusiveGroup

    short

    Specifies whether or not the group assigned to a field in a report is mutually exclusive. This variable does not apply if the m_partOfGroup member variable is set to FALSE. Set this variable to TRUE if it is mutually exclusive, FALSE if it is not, or PEP_UNCHANGED to keep the existing setting.

Constructor CRPEParameterValueInfo::CRPEParameterValueInfo

This constructs a CRPEParameterValueInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEPrameterValueInfo ();

Constructor Syntax
CRPEParameterValueInfo (

        short isNullable,

        short disallowEditing,

        short allowMultipleValues,

        short hasDiscreteValues,

        short partOfGroup,

        short groupNum,

        short mutuallyExclusiveGroup );


CRPEPrintOptions

This structure contains print options for a report and is used by CRPEJob::SetPrintOptions.

Data Members

Each data member is set by the corresponding constructor parameter unless otherwise noted.

Member | Type | Default | Description
m_startPageN | unsigned short | 0 | Specifies the first page that you want to print. Parameter is 1-based. Use 0 to preserve the existing setting.
m_stopPageN | unsigned short | 0 | Specifies the last page that you want to print. Parameter is 1-based. Use 0 to preserve the existing setting.
m_nReportCopies | unsigned short | 0 | Specifies the number of copies that you want to print. Parameter is 1-based. Use 0 to preserve the existing setting.
m_collation | unsigned short | PEP_ DEFAULT COLLATION | Indicates whether you want the copies of the report to be collated (if you are printing multiple copies of a multiple page report). Uses one of the following constants.
 | Constant |  | Description
 | PEP_UNCOLLATED |  | Page order = 1, 1, 1,...; 2, 2, 2,...; 3, 3, 3,...; etc.
 | PEP_COLLATED |  | Page order = 1, 2, 3,...; 1, 2, 3,...; 1, 2, 3,...; etc.
 | PEP_DEFAULTCOLLATION |  | Use the collation settings specified in the report.
Member | Type | Default | Description
m_outputFileName | _TCHAR | '\0' | Specifies the output file name.

Constructor CRPEPrintOptions::CRPEPrintOptions

This constructs a CRPEPrintOptions structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEPrintOptions ();

Constructor Syntax
CRPEPrintOptions (

        unsigned short startPageN,

        unsigned short stopPageN,

        unsigned short nReportCopies,

        unsigned short collation,

        _TCHAR *outputFileName );


CRPEReadingRecordsEventInfo

This structure provides information about records read when a callback function is called with event ID equal to PEP_READING_RECORDS_EVENT.

Data Members

Member | Type | Default | Description
m_cancelled | short | FALSE | BOOL. Indicates whether the reading records event is canceled.
m_recordsRead | long | 0 | Indicates how many records have been read so far.
m_recordsSelected | long | 0 | Indicates how many records have been selected so far.
m_done | short | FALSE | BOOL. Indicates whether the reading records event is finished.

Constructor CRPEReadingRecordsEventInfo::CRPEReadingRecordsEventInfo

This constructs a CRPEReadingRecordsEventInfo structure object. It assigns default values to the members of the structure.

Constructor Syntax

CRPEReadingRecordsEventInfo ();


CRPEReportFieldMappingInfo

This structure contains report field mapping information.

Data Members

Each data member is set by the corresponding constructor parameter unless otherwise noted.

Data Member | Type | Default | Description
m_valueType | WORD | 0 | valueType, one of the PEP_FVT constants.
 | Constant
 | PEP_FVT_INT8SFIELD
 | PEP_FVT_INT8UFIELD
 | PEP_FVT_INT16SFIELD
 | PEP_FVT_INT16UFIELD
 | PEP_FVT_INT32SFIELD
 | PEP_FVT_INT32UFIELD
 | PEP_FVT_NUMBERFIELD
 | PEP_FVT_CURRENCYFIELD
 | PEP_FVT_BOOLEANFIELD
 | PEP_FVT_DATEFIELD
 | PEP_FVT_TIMEFIELD
 | PEP_FVT_STRINGFIELD
 | PEP_FVT_TRANSIENTMEMOFIELD
 | PEP_FVT_PERSISTENTMEMOFIELD
 | PEP_FVT_BLOBFIELD
 | PEP_FVT_DATETIMEFIELD
 | PEP_FVT_BITMAPFIELD
 | PEP_FVT_ICONFIELD
 | PEP_FVT_PICTUREFIELD
 | PEP_FVT_OLEFIELD
 | PEP_FVT_GRAPHFIELD
 | PEP_FVT_UNKNOWNFIELD
Data Member | Type | Default | Description
m_TableAliasName | _TCHAR | '\0' | The table alias name (of length PEP_TABLE_NAME_LEN = 128).
m_databaseFieldName | _TCHAR | '\0' | The database field name (of length PEP_DATABASE_FIELD_NAME_LEN = 128).
m_mappingTo | int | 0 | The assigned index of a field in PEFieldMappingEventInfo. See Remarks below.

Remarks
  • Mapped fields are assigned to the index of a field in the member databaseFields array of PEFieldMappingEventInfo.
  • Unmapped fields are assigned to -1.
Constructor CRPEReportFieldMappingInfo::CRPEReportFieldMappingInfo

This constructs a CRPEReportFieldMappingInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEReportFieldMappingInfo ();

Constructor Syntax
CRPEReportFieldMappingInfo (

        WORD valueType,

        const _TCHAR *tableAliasName,

        const _TCHAR *databaseFieldName,

        int  mappingTo );


CRPEReportOptions

This structure contains specifications for formatting selected report sections. This information is used by the methods CRPEJob::GetReportOptions, and CRPEJob::SetReportOptions.

Data Members
  • Each data member is set by the corresponding constructor parameter.
  • Use TRUE, FALSE, or PEP_UNCHANGED for each member except as noted below.
  • The default for each data member is PEP_UNCHANGED.

    m_saveDataWithReport

    Specifies whether data should be saved with the report.

    m_saveSummaries
    WithReport

    Specifies whether to save summaries with the report.

    m_useIndexForSpeed

    Specifies whether to use index values.

    m_translateDOSStrings

    Specifies whether to translate DOS strings.

    m_translateDOSMemos

    Specifies whether to translate DOS memos.

    m_convertDateTimeType

    Specifies whether to convert Date/Time format to another format. Use one of the following constants or PEP_UNCHANGED.

            Constant Description

    PEP_RPTOPT_DVTDATETIMETODATE

    To Date.

    PEP_RPTOPT_KEEPDATETIME
    TYPE

    To Date/Time.

    m_convertNullFieldTo
    Default

    Specifies whether to convert NULL parameter fields to their default values.

    m_morePrintEngineError
    Messages

    Specifies whether to allow the print engine to pop up error messages to the screen from an application without the user's intervention.

    m_caseInsensitiveSQLData

    Specifies whether to perform a case insensitive search for SQL data.

    m_verifyOnEveryPrint

    Specifies whether to perform database verification for every print job.

    m_zoomMode

    Use one of the PEP_ZOOM_XXX Zoom Constants or PEP_UNCHANGED.

    m_hasGroupTree

    Specifies whether there is a group tree associated with the report.

    m_dontGenerateDataFor
    HiddenObjects

    Specifies whether to generate data for hidden objects.

    m_performGrouping
    OnServer

    Specifies whether to perform grouping on servers.

    m_doAsyncQuery

    Specifies whether to do Async Query.

    m_promptMode

    Specifies the prompt mode. Uses Report Prompt Option Constants.

    m_selectDistinctRecords

    Boolean. Specifies the select distinct records option.

Constructor CRPEReportOptions::CRPEReportOptions

This constructs a CRPEReportOptions structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEReportOptions ();

Constructor Syntax
CRPEReportOptions (

        short saveDataWithReport,

        short saveSummariesWithReport,

        short useIndexForSpeed,

        short translateDOSStrings,

        short translateDOSMemos,

        short convertDateTimeType,

        short convertNullFieldToDefault,

        short morePrintEngineErrorMessages,

        short caseInsensitiveSQLData,

        short verifyOnEveryPrint,

        short zoomMode,

        short hasGroupTree,

        short dontGenerateDataForHiddenObjects,

        short performGroupingOnServer,

        short doAsyncQuery,

        short promptMode,

        short selectDistinctRecords,

        short wysiwygMode );


CRPEReportSummaryInfo

This structure provides report summary information such as the report title, author, and comments. It corresponds to the report summary information in the Crystal Reports Designer. This structure is used by CRPEJob::GetReportSummaryInfo, to get information about a specific parameter field and by CRPEJob::SetReportSummaryInfo, to change a specific parameter field.

Data Members
  • Each data member is set by the corresponding constructor parameter unless otherwise noted.
  • The default value for each data member is '\0', except as noted.

    m_applicationName

    _TCHAR

    Specifies an application name (of size PEP_SI_APPLICATION_NAME_LEN = 128) for the application using this report.

    m_title

    _TCHAR

    Specifies the title (of size PEP_SI_TITLE_LEN = 128) of the current report.

    m_subject

    _TCHAR

    Specifies the subject (of size PEP_SI_SUBJECT_LEN = 128) of the current report.

    m_author

    _TCHAR

    Specifies the author (of size PEP_SI_AUTHOR_LEN = 128) of the current report.

    m_keywords

    _TCHAR

    Specifies the keywords (of size PEP_SI_KEYWORDS_LEN = 128) included for the current report.

    m_comments

    _TCHAR

    Specifies any comments (of size PEP_SI_COMMENTS_LEN = 512) for the current report.

    m_reportTemplate

    _TCHAR

    Specifies the report template (of size PEP_SI_REPORT_TEMPLATE_LEN = 128) for the current report.

    m_savePreview
    Picture

    short

    Specifies whether or not to save the Preview Picture. Default value = 0.

Constructor CRPEReportSummaryInfo:: CRPEReportSummaryInfo

This constructs a CRPEReportSummaryInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEReportSummaryInfo ();

Constructor Syntax
CRPEReportSummaryInfo (

        _TCHAR *applicationName,

        _TCHAR *title,

        _TCHAR *subject,

        _TCHAR *author,

        _TCHAR *keywords,

        _TCHAR *comments,

        _TCHAR *reportTemplate,

        short savePreviewPicture );


CRPESearchButtonClickedEventInfo

This structure returns information when a callback function is called with event ID equal to PEP_SEARCH_BUTTON_CLICKED_EVENT.

Data Members

Member | Type | Default | Description
m_windowHandle | long | 0 | Specifies on which frame window handle the button is positioned.
m_searchString | _TCHAR | '\0' | Specifies the search string (of length = PEP_SEARCH_STRING_LEN = 128) in search edit control.

Constructor
CRPESearchButtonClickedEventInfo::CRPESearchButtonClickedEventInfo

This constructs a CRPESearchButtonClickedEventInfo structure object. It assigns default values to the members of the structure.

Constructor Syntax

CRPESearchButtonClickedEventInfo ();


CRPESectionOptions

This structure contains specifications for formatting selected report sections and areas.

Data Members
  • Each data member is set by the corresponding constructor parameter.
  • The default for each member is FALSE except m_backgroundColour default PEP_UNCHANGED_COLOR.

    m_visible

    short

    Specifies whether or not the selected section is visible. Use TRUE to keep the section visible, FALSE to hide the section, or PEP_UNCHANGED to retain the previous setting.

    m_newPageBefore

    short

    Specifies whether or not the Crystal Report Engine will insert a page break before the section is printed. Use TRUE to insert a page break, FALSE to leave it without a page break, or PEP_UNCHANGED to retain the previous setting.

    m_newPageAfter

    short

    Specifies whether or not the Crystal Report Engine will insert a page break after the section is printed. Use TRUE to insert a page break, FALSE to leave it without a page break, or PEP_UNCHANGED to retain the previous setting.

    m_keepTogether

    short

    Specifies whether the Crystal Report Engine is to keep all lines of the section together, either on the current page (if there is room), or on the next page. Use TRUE to keep the lines together, FALSE to allow the Crystal Report Engine to split section data from one page to the next if necessary, or PEP_UNCHANGED to retain the previous setting.

    m_suppressBlank
    Lines

    short

    Specifies whether the Crystal Report Engine is to eliminate lines from your report that are blank due to fields being suppressed (zeroes, duplicates, and hidden fields). TRUE eliminates blank lines, FALSE retains them, or PEP_UNCHANGED retains the previous setting.

    m_resetPageN
    After

    short

    Specifies whether the Crystal Report Engine is to reset the page number to one (1) for the following page, after it prints a group total. Use TRUE to reset the page number, FALSE to continue the existing numbering, or PEP_UNCHANGED to retain the previous setting.

    m_printAtBottom
    OfPage

    short

    Specifies whether the Crystal Report Engine is to cause each group summary value to print only at the bottom of a page. Use TRUE to print summaries at the bottom of the page, FALSE to print summaries immediately after the group, or PEP_UNCHANGED to retain the previous setting.

    m_background
    Colour

    COLOREF

    Specifies the RGB color value contained in the structure, COLORREF. Use PEP_UNCHANGED_COLOR to retain the previous settings.

    m_underlaySection

    short

    Indicates whether the specified section is to use the underlay feature for chart and map placement. Use TRUE to underlay. Use PEP_UNCHANGED to retain the previous setting.

    m_showArea

    short

    Indicates whether to show/hide the Area to which the specified section belongs. Use TRUE to show the specified Area, FALSE to hide it, or PEP_UNCHANGED to retain the previous setting.

    m_freeForm
    Placement

    short

    Design time flag. If set to TRUE an object can be placed anywhere in a section. Use PEP_UNCHANGED to retain the previous setting.

    m_reserveMinimum
    PageFooter

    short

    Used to reduce unnecessary white space in the page footer area containing more than one conditionally formatted section . When set to TRUE, the space required to display only one section (the tallest) is reserved. When set to FALSE (default), the maximum height necessary to display every section in the page footer area at full height will be reserved. See Remarks below.

Remarks

reserveMinimumPageFooter can be used to remove undesirable white space when there are two or more sections in the page footer area and only one section, based on conditional settings, will be visible when the report is viewed in the preview window. For example, a report page footer area might contain two sections, one conditionally set to display at the bottom of odd pages and the other at the bottom of even pages. When this member is set to TRUE, sufficient space will be reserved to display only one of the sections included in the area (set to the height of the tallest section). Note that when reserveMinimumPageFooter = TRUE and there is more than one section visible in the page footer area, the visible sections will be displayed only to the extent allowed by the reserved minimum space (the height of the tallest section) with the remainder truncated.

Constructor CRPESectionOptions::CRPESectionOptions

This constructs a CRPESectionOptions structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPESectionOptions ();

Constructor Syntax
CRPESectionOptions (

        short visible,

        short newPageBefore,

        short newPageAfter,

        short keepTogether,

        short suppressBlankLines,

        short resetPageNAfter,

        short printAtBottomOfPage,

        COLORREF backgroundColour,

        short underlaySection,

        short showArea,

        short freeFormPlacement,

        short reserveMinimumPageFooter );

CRPESessionInfo

This structure is used to get and set the session information (user ID and password) for password-protected Microsoft Access databases. It is used with CRPEJob::GetNthTableSessionInfo, and CRPEJob::SetNthTableSessionInfo, member functions.

Data Members

Member | Type | Default | Description
m_userID | _TCHAR | '\0' | Specifies the user ID (of length PEP_SESS_USERID_LEN = 128) needed for logging on to the MS Access system (NULL-terminated).
m_password | _TCHAR | '\0' | Specifies the password (of length PEP_SESS_PASSWORD_LEN = 128) needed for logging on to the MS Access system (NULL-terminated).
m_session Handle | DWORD | 0 | The handle to the current MS Access session. When getting information from a report, sessionHandle is undefined. When setting information for a report, if sessionHandle is = 0 then the UserID and Password settings are used; otherwise the SessionHandle is used.

Constructor CRPESessionInfo::CRPESessionInfo

This constructs a CRPESessionInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPESessionInfo ();

Constructor Syntax
CRPESessionInfo (

        const _TCHAR *userID,

        const _TCHAR *password,

        DWORD sessionHandle );
CRPEShowGroupEventInfo

This structure provides show group event information when an event callback is called with event ID equal to PEP_SHOW_GROUP_EVENT.

Data Members

Member | Type | Default | Description
m_groupLevel | WORD | 0 | Number of items in groupList.
m_windowHandle | long | 0 | Frame window handle where the event happens.
m_groupList | _TCHAR | NULL | Pointer to an array of group names describing the group path that the group area is going to navigate to. This pointer is freed after the callback function.

Constructor CRPEShowGroupEventInfo::CRPEShowGroupEventInfo

This constructs a CRPEShowGroupEventInfo structure object. It assigns default values to the members of the structure.


Constructor Syntax

CRPEShowGroupEventInfo ();


CRPEStartEventInfo

This structure provides start event information when the callback function is called with event ID equal to PEP_START_EVENT.

Data Members

The default for data member m_destination is PEP_TO_NOWHERE.

m_destination

WORD

Indicates the process destination using one of the following PEP_TO_XXX Job Destination Constants.

Constructor CRPEStartEventInfo::CRPEStartEventInfo

This constructs a CRPEStartEventInfo structure object. It assigns the default value to the member of the structure.

Constructor Syntax

CRPEStartEventInfo ();


CRPEStopEventInfo

This structure provides stop event information when a callback method is called with an event ID equal to PEP_STOP_EVENT.

Data Members

m_destination | WORD | Indicates the process destination using one of the PEP_TO_XXX Job Destination Constants.
m_jobStatus | WORD | Indicates the current status of the job using one of the PEP_JOBXXX Job Status Constants.

Constructor CRPEStopEventInfo::CRPEStopEventInfo

This constructs a CRPEStopEventInfo structure object. It assigns default values to the members of the structure.

Constructor Syntax

CRPEStopEventInfo ();


CRPESubreportInfo

The CRPESubreportInfo structure contains information on a subreport that appears in the main report. This structure is used by CRPEJob::GetSubreportInfo, to retrieve information about a subreport.

Data Members

Member | Type | Default | Description
m_name | _TCHAR | '\0' | A string (of length PEP_SUBREPORT_NAME_LEN = 128) that contains the specified subreport name.
m_NLinks | short | 0 | Indicates the number of links that are present in the specified subreport.
m_IsOn Demand | short | FALSE | Indicates whether the specified subreport is available to the user on demand. Set to TRUE if the subreport is available on demand, FALSE if it is not, and PEP_UNCHANGED to retain the previous setting.
m_external | short | FALSE | Specifies TRUE if the subreport is imported and FALSE otherwise.
m_reimport Option | short | PEP_UNCHANGED | Specifies the reimport option using one of the PEP_SRI_XXX Subreport Info Constants.

Constructor CRPESubreportInfo::CRPESubreportInfo

This constructs a CRPESubreportInfo structure object. It assigns default values to the members of the structure.

Constructor Syntax

CRPESubreportInfo();

CRPETableDifferenceInfo

This structure contains table difference information and is used by CRPEJob::CheckNthTableDifferences.

Data Member

Each data member is set by the corresponding constructor parameter unless otherwise noted.

Member | Type | Default | Description
m_tableDifferences | DWORD | 0 | Contains any combination of PEP_TCD_XXX Table Difference Constants.
m_reserved1 | DWORD |  | Reserved. Do not use.
m_reserved2 | DWORD |  | Reserved. Do not use.

Constructor CRPETableDifferenceInfo::CRPETableDifferenceInfo

This constructs a CRPETableDifferenceInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPETableDifferenceInfo ();

Constructor Syntax
CRPETableDifferenceInfo (

        WORD StructSize,

        DWORD tableDifferences );


CRPETableLocation

This structure contains table location information and is used by CRPEJob::GetNthTableLocation, and CRPEJob::SetNthTableLocation.

Data Member

Each data member is set by the corresponding constructor parameter unless otherwise noted.

Member | Type | Default | Description
m_location | _TCHAR | '\0' | Specifies a pointer to the string (of length PEP_TABLE_LOCATION_LEN = 256) that contains the database location (NULL-terminated).
m_SubLocation | _TCHAR | '\0' | Specifies a pointer to the string (of length PEP_TABLE_LOCATION_LEN = 256) that contains the database sublocation (NULL-terminated).
m_ConnectBuffer | _TCHAR | '\0' | Specifies a pointer to the string (of length PEP_CONNECTION_BUFFER_LEN = 512) that contains the database connection buffer (NULL-terminated).

Constructor CRPETableLocation::CRPETableLocation

This constructs a CRPETableLocation structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPETableLocation ();

Constructor Syntax
CRPETableLocation (

        const _TCHAR *location,

        const _TCHAR *SubLocation,

        const _TCHAR *ConnectionBuffer );


CRPETablePrivateInfo

This structure contains information for using data objects such as ADO, RDO, or CDO with the Active Data Driver.

Data Member

Each data member is set by the corresponding constructor parameter unless otherwise noted.

Member | Type | Description
m_nBytes | WORD | Specifies the length of the data starting at the dataPtr.
m_tag | DWORD | Specifies a value indicating the type of data being passed to theDatabaseTable object in the Data parameter. Currently, the only possible value is 3. This value must be used for all Active data sources including DAO, ADO, RDO, CDO, and the Visual Basic data control.
m_dataPtr | BYTE | Specifies a pointer to variant data passed to the database driver. With Active data, this must be a Recordset object if DAO, ADO, or the Visual Basic data control is used. If CDO is used, this must be a Rowset object.

Constructor CRPETablePrivateInfo::CRPETablePrivateInfo

This constructs a CRPETablePrivateInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPETablePrivateInfo ();

Constructor Syntax
CRPETablePrivateInfo (

        WORD StructSize,

        WORD nBytes,

        DWORD tag,

        BYTE *dataPtr );


CRPETableType

This structure contains information about a specific table used in the report and is used by CRPEJob::GetNthTableSessionInfo.

Data Members

Member | Type | Default | Description
m_dllName | _TCHAR | '\0' | Specifies the name of the appropriate database DLL (of length PEP_DLL_NAME = 64) for the table of interest (NULL-terminated).
m_descriptiveName | _TCHAR | '\0' | Specifies the name of the database table (of length PEP_FULL_NAME = 256) of interest (NULL-terminated).
m_dbType | WORD | PEP_DT_SQL | Specifies the type of database that contains the table of interest. Use one of the following constants.
 | Constant |  | Description
 | PEP_DT_STANDARD |  | Standard data table.
 | PEP_DT_SQL |  | SQL data table.

Constructor CRPETableType::CRPETableType

This constructs a CRPETableType structure object. It assigns default values to the members of the structure.

Constructor Syntax

CRPETableType ();


CRPETrackCursorInfo

This structure specifies cursor information such as size and type and is used by CRPEJob::GetTrackCursorInfo, or CRPEJob::SetTrackCursorInfo.

Data Members
  • Each available data member uses the PEP_TC_XXX Cursor Constants, except as noted below.
  • The default value for each available data member is PEP_TC_DEFAULT_CURSOR, except as noted below. For most areas, CRPE sets this to PEP_TC_ARROW_CURSOR.
  • Pass PE_UNCHANGED for any available data member to use the existing cursor.

    Member Type Description

    m_groupAreaCursor:

    short

    Specifies the group area cursor.

    m_groupAreaFieldCursor

    short

    Specifies the cursor for a memo, blob, database, summary, or formula field in the group area.

    m_detailAreaCursor

    short

    Specifies the cursor for the Details area.

    m_detailAreaFieldCursor

    short

    Specifies the cursor for a memo, blob, database, summary, or formula field in the Details area.

    m_graphCursor

    short

    Specifies the cursor for the group chart in the Report Header or Report Footer area.

    m_groupAreaCursorHandle

    long

    Reserved, do not use.

    m_groupAreaFieldCursorHandle

    long

    Reserved, do not use.

    m_detailAreaCursorHandle

    long

    Reserved, do not use.

    m_detailAreaFieldCursorHandle

    long

    Reserved, do not use.

    m_graphCursorHandle

    long

    Reserved, do not use.

    m_ondemandSubreportCursor

    short

    Specifies the cursor for real-time subreports when drilldown for the window is enabled. Default is PEP_TC_MAGNIFY_CURSOR.

    m_hyperlinkCursor

    short

    Specifies the cursor to show over a report object that has hyperlink text. Default is PEP_TC_HAND_CURSOR.

Remarks
  • By default, most of the cursors are set to the constant PEP_TC_ARROW_CURSOR. If the canDrillDown option in CRPEWindowOptions is set to True, groupAreaCursor, groupAreaFieldCursor, and graphCursor will be PEP_TC_MAGNIFY_CURSOR.
  • Some cursors are 32-bit only and some are 16-bit only. If a cursor is not supported on a platform, the cursor will not be changed for the specified area.
Constructor CRPETrackCursorInfo::CRPETrackCursorInfo

This constructs a RPETrackCursorInfo structure object. It assigns default values to the members of the structure.

Constructor Syntax

CRPETrackCursorInfo () ;


CRPEValueInfo

This structure contains parameter field value information.

Data Members

Each data member is set by the corresponding constructor parameter.

Member | Type | Default | Description
m_valueType | WORD | PEP_VI_ NUMBER | Specifies the data type of the parameter field. The Crystal Report Engine supports the following data types and associated constants.
 |  | Data Type | Constant
 |  | Number | PEP_VI_NUMBER
 |  | Currency | PEP_VI_CURRENCY
 |  | Boolean | PEP_VI_BOOLEAN
 |  | Date | PEP_VI_DATE
 |  | String | PEP_VI_STRING
 |  | Date/Time | PEP_VI_DATETIME
 |  | Time | PEP_VI_TIME
 |  | Integer | PEP_VI_INTEGER
 |  | Color | PEP_VI_COLOR
 |  | Char | PEP_VI_CHAR
 |  | Long | PEP_VI_LONG
 |  | NoValue | PEP_VI_NOVALUE
Member | Type | Default | Description
m_viNumber | double | 0 | Specifies the value if the parameter is a numeric value.
m_viCurrency | double | 0 | Specifies the value if the parameter is a currency value.
m_viBoolean | BOOL | FALSE | Specifies the value if the parameter is a Boolean value.
m_viString | _TCHAR | \0' | Specifies the string (of length PEP_VI_STRING_LEN = 256, NULL-terminated) value if the parameter is a string
m_viDate | short | 0, 0, 0 | Specifies the value if the parameter is a date value (year, month, day).
m_viDate Time | short | 0, 0, 0, 0, 0, 0 | Specifies the value if the parameter is a date/time value (year, month, day, hour, minute, second).
m_viTime | short | 0, 0, 0 | Specifies the value if the parameter is a time value (hour, minute, second).
m_viColor | COLOREF | 0X00000000 | For future support of color parameters.
m_viInteger | short | 0 | For future support of integer parameters.
m_viC | _TCHAR | '\0' | For future support of character parameters.
m_ignored | _TCHAR | '\0' | For 4 byte alignment. Ignored. Do not use.
m_viLong | long | 0 | For future support of long parameters.

Constructor CRPEValueInfo::CRPEValueInfo

This constructs a CRPEValueInfo structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEValueInfo ();

Constructor Syntax
CRPEValueInfo (

        WORD StructSize,

        WORD valueType,

        double viNumber,

        double viCurrency,

        BOOL viBoolean,

        _TCHAR viString,

        short viDate,

        short viDateTime,

        short viTime,

        COLORREF viColor,

        short viInteger,

        _TCHAR viC,

        _TCHAR ignored,

        long viLong );


CRPEWindowOptions

This structure is used to set attributes for a print window. Use CRPEJob::GetWindowOptions, and CRPEJob::SetWindowOptions, to retrieve and change these options.

Data Members
  • The default for each data member is FALSE.
  • For each data member, use TRUE, FALSE, or PEP_UNCHANGED to use existing setting.

    m_hasGroupTree

    short

    Indicates whether the specified print window has a group tree.

    m_canDrillDown

    short

    Indicates whether the specified print window has permission to drill down.

    m_has NavigationControls

    short

    Indicates whether the specified print window has navigation controls (previous, next, etc.).

    m_hasCancelButtom

    short

    Indicates whether the specified print window has a Cancel button.

    m_hasPrintButton

    short

    Indicates whether the specified print window has a Print button.

    m_hasExportButton

    short

    Indicates whether the specified print window has an Export button.

    m_has ZoomControl

    short

    Indicates whether the specified print window has magnification controls.

    m_hasCloseButton

    short

    Indicates whether the specified print window has a Close button.

    m_has progressControls

    short

    Indicates whether the specified print window has controls to indicated the progress of a lengthy operation.

    m_hasSearchButton

    short

    Indicates whether to perform database verification for every print job.

    m_hasPrintSetup
    Button

    short

    Indicates whether the specified print window has a Print Setup button.

    m_hasRefreshButton

    short

    Indicates whether the specified print window has a Refresh Data button.

    m_showToolbarTips

    short

    Indicates whether Toolbar Tips will be shown or hidden.

    m_showDocumentTips

    short

    Indicates whether Document Tips will be shown or hidden.

    m_hasLaunchButton

    short

    Indicates whether a Launch Seagate Analysis button will be shown or hidden.

    Note: Seagate Analysis is now known as Crystal Analysis.

Constructor CRPEWindowOptions::CRPEWindowOptions

This constructs a CRPEWindowOptions structure object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Syntax (Default)

CRPEReportOptions ();

Constructor Syntax
CRPEWindowOptions (

        short hasGroupTree,

        short canDrillDown,

        short hasNavigationControls,

        short hasCancelButton,

        short hasPrintButton,

        short hasExportButton,

        short hasZoomControl,

        short hasCloseButton,

        short hasProgressControls,

        short hasSearchButton,

        short hasPrintSetupButton,

        short hasRefreshButton

        short showToolbarTips,

        short showDocumentTips,

        short hasLaunchButton );


CRPEZoomLevelChangingEventInfo

This structure gives information about the PEP_ZOOM_LEVEL_CHANGING_EVENT event.

Data Members

m_zoomLevel | WORD | The zoom level you wish to set the preview window at. This value can be a value from 25 to 400, indicating a magnification percentage, or it can be one of the PEP_ZOOM_XXX Zoom Constants.
m_windowHandle | long | Specifies the frame window handle where the event happens.

Constructor
CRPEZoomLevelChangingEventInfo::CRPEZoomLevelChangingEventInfo

This constructs a CRPEZoomLevelChangingEventInfo structure object. It assigns default values to the members of the structure.

Constructor Syntax

CRPEZoomLevelChangingEventInfo ();


class CRPEngine and class CRPEJob Constants

This section describes some of the more widely used class CRPEngine and class CRPEJob constants.

Area/Section Format Formula Constants

Cursor Constants

Error Codes

Event Id Constants

Formula Syntax Constants

Graph Options Constants

    • Graph Axis Division Method Constants
    • Graph Placement Constants
    • Graph Gridline Constants
    • Graph Bar Size Constants
    • Graph Pie Size Constants
    • Graph Detached Pie Slice Constants
    • Graph Legend Layout Constants
    • Graph Marker Size Constants
    • Graph Marker Shape Constants
    • Graph Color Constants
    • Chart Data Point Constants
    • Chart Number Format Constants
    • Graph Viewing Angle Constants

Graph Title Type Constants

Graph Text Font Constants

Graph Type and Subtype Constants

    • Graph Major Type Constants
    • Bar Chart Subtype Constants
    • Line Chart Subtype Constants
    • Area Chart Subtype Constants
    • Pie Chart Subtype Constants
    • Doughnut Chart Subtype Constants
    • 3D Riser Chart Subtype Constants
    • 3D Surface Chart Subtype Constants
    • Scatter Chart Subtype Constants
    • Radar Chart Subtype Constants
    • Bubble Chart Subtype Constants
    • Stock (High/Low/Close) Chart Subtype Constants
    • Miscellaneous Chart Subtype Constants

Job Destination Constants

Job Status Constants

Report Prompt Option Constants

Section Codes Constants

Sort Method Constants

Sort Order Constants

Subreport Info Constants

Table Difference Constants

Zoom Constants


Area/Section Format Formula Constants

Constants PE_FFN_SECTION_VISIBILITY and PEP_FFN_SECTION_BACK_COLOUR are included for support of older applications. These constants have the same value as PE_FFN_AREASECTION_VISIBILITY and PEP_FFN_SECTION_BACK_COLOR. All new Crystal Reports applications should use PE_FFN_AREASECTION_VISIBILITY and PEP_FFN_SECTION_BACK_COLOR.

Constant | Description
PE_FFN_AREASECTION_VISIBILITY | Area and Section format
PE_FFN_SECTION_VISIBILITY | Section format
PE_FFN_SHOW_AREA | Area format
PE_FFN_NEW_PAGE_BEFORE | Area and Section format
PE_FFN_NEW_PAGE_AFTER | Area and Section format
PE_FFN_KEEP_TOGETHER | Area and Section format
PE_FFN_SUPPRESS_BLANK_SECTION | Section format
PE_FFN_RESET_PAGE_N_AFTER | Area and Section format
PE_FFN_PRINT_AT_BOTTOM_OF_PAGE | Area and Section format
PE_FFN_UNDERLAY_SECTION | Section format
PE_FFN_SECTION_BACK_COLOUR | Section format
PE_FFN_SECTION_BACK_COLOR | Section format


Cursor Constants

Constant | Value | Description
PEP_TC_DEFAULT_CURSOR | 0 | CRPE set default cursor to be PEP_TC_ARROW_CURSOR
PEP_TC_ARROW_CURSOR | 1 | CRPE default cursor
PEP_TC_CROSS_CURSOR | 2 |
PEP_TC_IBEAM_CURSOR | 3 |
PEP_TC_UPARROW_CURSOR | 4 |
PEP_TC_SIZEALL_CURSOR | 5 |
PEP_TC_SIZENWSE_CURSOR | 6 |
PEP_TC_SIZENESW_CURSOR | 7 |
PEP_TC_SIZEWE_CURSOR | 8 |
PEP_TC_SIZENS_CURSOR | 9 |
PEP_TC_NO_CURSOR | 10 |
PEP_TC_WAIT_CURSOR | 11 |
PEP_TC_APPSTARTING_CURSOR | 12 |
PEP_TC_HELP_CURSOR | 13 |
PEP_TC_SIZE_CURSOR | 14 | For 16bit
PEP_C_ICON_CURSOR | 15 | For 16bit
PEP_TC_BACKGROUND_PROCESS_CURSOR | 94 | CRPE specific cursor.
PEP_TC_GRAB_HAND_CURSOR | 95 | CRPE specific cursor.
PEP_TC_ZOOM_IN_CURSOR | 96 | CRPE specific cursor.
PEP_TC_REPORT_SECTION_CURSOR | 97 | CRPE specific cursor.
PEP_TC_HAND_CURSOR | 98 | CRPE specific cursor.
PEP_TC_MAGNIFY_CURSOR | 99 | CRPE specific cursor.


Error Codes

The following codes are returned by CRPEngine::GetErrorCode, and CRPEJob::GetErrorCode.

Constant | Description
PEP_ERR_NOERROR |
PEP_ERR_NOTENOUGHMEMORY |
PEP_ERR_INVALIDJOBNO |
PEP_ERR_INVALIDHANDLE |
PEP_ERR_STRINGTOOLONG |
PEP_ERR_NOSUCHREPORT |
PEP_ERR_NODESTINATION |
PEP_ERR_BADFILENUMBER |
PEP_ERR_BADFILENAME |
PEP_ERR_BADFIELDNUMBER |
PEP_ERR_BADFIELDNAME |
PEP_ERR_BADFORMULANAME |
PEP_ERR_BADSORTDIRECTION |
PEP_ERR_ENGINENOTOPEN |
PEP_ERR_INVALIDPRINTER |
PEP_ERR_PRINTFILEEXISTS |
PEP_ERR_BADFORMULATEXT |
PEP_ERR_BADGROUPSECTION |
PEP_ERR_ENGINEBUSY |
PEP_ERR_BADSECTION |
PEP_ERR_NOPRINTWINDOW |
PEP_ERR_JOBALREADYSTARTED |
PEP_ERR_BADSUMMARYFIELD |
PEP_ERR_NOTENOUGHSYSRES |
PEP_ERR_BADGROUPCONDITION |
PEP_ERR_JOBBUSY |
PEP_ERR_BADREPORTFILE |
PEP_ERR_NODEFAULTPRINTER |
PEP_ERR_SQLSERVERERROR |
PEP_ERR_BADLINENUMBER |
PEP_ERR_DISKFULL |
PEP_ERR_FILEERROR |
PEP_ERR_INCORRECTPASSWORD |
PEP_ERR_BADDATABASEDLL |
PEP_ERR_BADDATABASEFILE |
PEP_ERR_ERRORINDATABASEDLL |
PEP_ERR_DATABASESESSION |
PEP_ERR_DATABASELOGON |
PEP_ERR_DATABASELOCATION |
PEP_ERR_BADSTRUCTSIZE |
PEP_ERR_BADDATE |
PEP_ERR_BADEXPORTDLL |
PEP_ERR_ERRORINEXPORTDLL |
PEP_ERR_PREVATFIRSTPAGE |
PEP_ERR_NEXTATLASTPAGE |
PEP_ERR_CANNOTACCESSREPORT |
PEP_ERR_USERCANCELLED |
PEP_ERR_OLE2NOTLOADED |
PEP_ERR_BADCROSSTABGROUP |
PEP_ERR_NOCTSUMMARIZEDFIELD |
PEP_ERR_DESTINATIONNOTEXPORT |
PEP_ERR_INVALIDPAGENUMBER |
PEP_ERR_NOTSTOREDPROCEDURE |
PEP_ERR_INVALIDPARAMETER |
PEP_ERR_GRAPHNOTFOUND |
PEP_ERR_INVALIDGRAPHTYPE |
PEP_ERR_INVALIDGRAPHDATA |
PEP_ERR_CANNOTMOVEGRAPH |
PEP_ERR_INVALIDGRAPHTEXT |
PEP_ERR_INVALIDGRAPHOPT |
PEP_ERR_BADSECTIONHEIGHT |
PEP_ERR_BADVALUETYPE |
PEP_ERR_INVALIDSUBREPORTNAME |
PEP_ERR_NOPARENTWINDOW | No dialog parent window.
PEP_ERR_INVALIDZOOMFACTOR | Invalid zoom factor.
PEP_ERR_PAGESIZEOVERFLOW |
PEP_ERR_LOWSYSTEMRESOURCES |
PEP_ERR_BADGROUPNUMBER |
PEP_ERR_INVALIDOBJECTFORMATNAME |
PEP_ERR_INVALIDNEGATIVEVALUE |
PEP_ERR_INVALIDMEMORYPOINTER |
PEP_ERR_INVALIDOBJECTTYPE |
PEP_ERR_INVALIDGRAPHDATATYPE |
PEP_ERR_INVALIDSUBREPORTLINKNUMBER |
PEP_ERR_SUBREPORTLINKEXIST |
PEP_ERR_BADROWCOLVALUE |
PEP_ERR_INVALIDSUMMARYNUMBER |
PEP_ERR_INVALIDGRAPHDATAFIELDNUMBER |
PEP_ERR_INVALIDSUBREPORTNUMBER |
PEP_ERR_INVALIDFIELDSCOPE |
PEP_ERR_FIELDINUSE |
PEP_ERR_INVALIDPARAMETERNUMBER |
PEP_ERR_INVALIDPAGEMARGINS |
PEP_ERR_REPORTONSECUREQUERY |
PEP_ERR_CANNOTOPENSECUREQUERY |
PEP_ERR_INVALIDSECTIONNUMBER |
PEP_ERR_SQLSERVERNOTOPENED |
PEP_ERR_TABLENAMEEXIST |
PEP_ERR_INVALIDCURSOR |
PEP_ERR_FIRSTPASSNOTFINISHED |
PEP_ERR_CREATEDATASOURCE |
PEP_ERR_CREATEDRILLDOWNPARAMETERS |
PEP_ERR_CHECKFORDATASOURCECHANGES |
PEP_ERR_STARTBACKGROUNDPROCESSING |
PEP_ERR_SQLSERVERINUSE |
PEP_ERR_GROUPSORTFIELDNOTSET |
PEP_ERR_CANNOTSETSAVESUMMARIES |
PEP_ERR_LOADOLAPDATABASEMANAGER |
PEP_ERR_OPENOLAPCUBE |
PEP_ERR_READOLAPCUBEDATA |
PEP_ERR_CANNOTSAVEQUERY |
PEP_ERR_CANNOTREADQUERYDATA |
PEP_ERR_MAINREPORTFIELDLINKED |
PEP_ERR_INVALIDMAPPINGTYPEVALUE |
PEP_ERR_HITTESTFAILED |
PEP_ERR_BADSQLEXPRESSIONNAME | No SQL expression by the specified *name* exists in this report.
PEP_ERR_BADSQLEXPRESSIONNUMBER | No SQL expression by the specified *number* exists in this report.
PEP_ERR_BADSQLEXPRESSIONTEXT | Not a valid SQL expression.
PEP_ERR_INVALIDDEFAULTVALUEINDEX | Invalid index for default value of a parameter.
PEP_ERR_NOMINMAXVALUE | The specified PEP_PF_XXX type does not have min/max values.
PEP_ERR_INCONSISTANTTYPES | Both min and max values are specified in PESetParameterMinMaxValue and the value types for the min and max values are not the same.
PEP_ERR_CANNOTLINKTABLES |
PEP_ERR_CREATEROUTER |
PEP_ERR_INVALIDFIELDINDEX |
PEP_ERR_INVALIDGRAPHTITLETYPE |
PEP_ERR_INVALIDGRAPHTITLEFONTTYPE |
PEP_ERR_PARAMTYPEDIFFERENT | The type used in an add/set value API for a parameter differs with its existing type.
PEP_ERR_INCONSISTANTRANGETYPES | The value type for both start & end range values must be the same.
PEP_ERR_RANGEORDISCRETE | An operation was attempted on a discrete parameter that is only legal for range parameters or vice versa.
PEP_ERR_NOTMAINREPORT | An operation was attempted that is disallowed for subreports.
PEP_ERR_INVALIDCURRENTVALUEINDEX | Invalid index for current value of a parameter.
PEP_ERR_LINKEDPARAMVALUE | Operation illegal on linked parameter.
PEP_ERR_INVALIDPARAMETERRANGEINFO | Invalid PEP_RI_XXX combination
PEP_ERR_INVALIDSORTMETHODINDEX | Invalid sort method index.
PEP_ERR_INVALIDGRAPHSUBTYPE | Invalid PEP_GST_XXX or PEP_GST_XXX does not match PEP_GT_XXX or PEP_GST_XXX current graph type.
PEP_ERR_BADGRAPHOPTIONINFO | One of the members of PEGraphOptionInfo is out of range.
PEP_ERR_BADGRAPHAXISINFO | One of them members of PEGraphAxisInfo is out of range.
PEP_ERR_NOTEXTERNALSUBREPORT | The subreport is not imported.
PEP_ERR_INVALIDPARAMETERVALUE |
PEP_ERR_INVALIDFORMULASYNTAXTYPE | Specified formula syntax not in PEP_FS_XXX.
PEP_ERR_INVALIDCROPVALUE |
PEP_ERR_INVALIDCOLLATIONVALUE |
PEP_ERR_STARTPAGEGREATERSTOPPAGE |
PEP_ERR_OTHERERROR |
PEP_ERR_INTERNALERROR | Programming error.
PEP_ERR_NOTIMPLEMENTED |


Event Id Constants

Constant | Description
PEP_CLOSE_PRINT_WINDOW_EVENT |
PEP_ACTIVATE_PRINT_WINDOW_EVENT |
PEP_DEACTIVATE_PRINT_WINDOW_EVENT |
PEP_PRINT_BUTTON_CLICKED_EVENT |
PEP_EXPORT_BUTTON_CLICKED_EVENT |
PEP_ZOOM_LEVEL_CHANGING_EVENT |
PEP_FIRST_PAGE_BUTTON_CLICKED_EVENT |
PEP_PREVIOUS_PAGE_BUTTON_CLICKED_EVENT |
PEP_NEXT_PAGE_BUTTON_CLICKED_EVENT |
PEP_LAST_PAGE_BUTTON_CLICKED_EVENT |
PEP_CANCEL_BUTTON_CLICKED_EVENT |
PEP_CLOSE_BUTTON_CLICKED_EVENT |
PEP_SEARCH_BUTTON_CLICKED_EVENT |
PEP_GROUP_TREE_BUTTON_CLICKED_EVENT |
PEP_PRINT_SETUP_BUTTON_CLICKED_EVENT |
PEP_REFRESH_BUTTON_CLICKED_EVENT |
PEP_SHOW_GROUP_EVENT |
PEP_DRILL_ON_GROUP_EVENT | Include drill on graph.
PEP_DRILL_ON_DETAIL_EVENT |
PEP_READING_RECORDS_EVENT |
PEP_START_EVENT |
PEP_STOP_EVENT |
PEP_MAPPING_FIELD_EVENT |
PEP_RIGHT_CLICK_EVENT | Right mouse click.
PEP_LEFT_CLICK_EVENT | Left mouse click.
PEP_MIDDLE_CLICK_EVENT | Middle mouse click.
PEP_DRILL_ON_HYPERLINK_EVENT |
PEP_LAUNCH_SEAGATE_ANALYSIS_EVENT |


Formula Syntax Constants

Constant | Value
PEP_FST_CRYSTAL | 0
PEP_FST_BASIC | 1


Graph Options Constants

The following Graph (Chart) Options Constants are listed in this section.

Graph Axis Division Method Constants

Graph Placement Constants

Graph Gridline Constants

Graph Bar Size Constants

Graph Pie Size Constants

Graph Detached Pie Slice Constants

Graph Legend Layout Constants

Graph Marker Size Constants

Graph Marker Shape Constants

Graph Color Constants

Chart Data Point Constants

Chart Number Format Constants

Graph Viewing Angle Constants


Graph Axis Division Method Constants

Constant | Value
PEP_ADM_AUTOMATIC | 0
PEP_ADM_MANUAL | 1


Graph Placement Constants

Constant

PEP_GLP_PLACEUPPERRIGHT

PEP_GLP_PLACEBOTTOMCENTER

PEP_GLP_PLACETOPCENTER

PEP_GLP_PLACERIGHT

PEP_GLP_PLACELEFT


Graph Gridline Constants

Constant

PEP_GGT_NOGRIDLINES

PEP_GGT_MINORGRIDLINES

PEP_GGT_MAJORGRIDLINES

PEP_GGT_MAJORANDMINORGRIDLINES


Graph Bar Size Constants

Constant

PEP_GBS_MINIMUMBARSIZE

PEP_GBS_SMALLBARSIZE

PEP_GBS_AVERAGEBARSIZE

PEP_GBS_LARGEBARSIZE

PEP_GBS_MAXIMUMBARSIZE


Graph Pie Size Constants

Constant

PEP_GPS_MINIMUMPIESIZE

PEP_GPS_SMALLPIESIZE

PEP_GPS_AVERAGEPIESIZE

PEP_GPS_LARGEPIESIZE

PEP_GPS_MAXIMUMPIESIZE


Graph Detached Pie Slice Constants

Constant

PEP_GDPS_NODETACHMENT

PEP_GDPS_SMALLESTSLICE

PEP_GDPS_LARGESTSLICE


Graph Legend Layout Constants

Constant | Value | Description
PEP_GLL_PERCENTAGE | 0 |
PEP_GLL_AMOUNT | 1 |
PEP_GLL_CUSTOM | 2 | Use for PEGetGraphOptionInfo. Do not use in PESetGraphOptionInfo.


Graph Marker Size Constants

Constant

PEP_GMS_SMALLMARKERS

PEP_GMS_MEDIUMSMALLMARKERS

PEP_GMS_MEDIUMMARKERS

PEP_GMS_MEDIUMLARGEMARKERS

PEP_GMS_LARGEMARKERS


Graph Marker Shape Constants

Constant

PEP_GMSP_RECTANGLESHAPE

PEP_GMSP_CIRCLESHAPE

PEP_GMSP_DIAMONDSHAPE

PEP_GMSP_TRIANGLESHAPE


Graph Color Constants

Constant

PEP_GCR_COLORCHART

PEP_GCR_BLACKANDWHITECHART


Chart Data Point Constants

Constant

PEP_GDP_NONE

PEP_GDP_SHOWLABEL

PEP_GDP_SHOWVALUE


Chart Number Format Constants

Constant

PEP_GNF_NODECIMAL

PEP_GNF_ONEDECIMAL

PEP_GNF_TWODECIMAL

PEP_GNF_CURRENCYNODECIMAL

PEP_GNF_CURRENCYTWODECIMAL

PEP_GNF_PERCENTNODECIMAL

PEP_GNF_PERCENTONEDECIMAL

PEP_GNF_PERCENTTWODECIMAL


Graph Viewing Angle Constants

Constant

PEP_GVA_STANDARDVIEW

PEP_GVA_TALLVIEW

PEP_GVA_TOPVIEW

PEP_GVA_DISTORTEDVIEW

PEP_GVA_SHORTVIEW

PEP_GVA_GROUPEYEVIEW

PEP_GVA_GROUPEMPHASISVIEW

PEP_GVA_FEWSERIESVIEW

PEP_GVA_FEWGROUPSVIEW

PEP_GVA_DISTORTEDSTDVIEW

PEP_GVA_THICKGROUPSVIEW

PEP_GVA_SHORTERVIEW

PEP_GVA_THICKSERIESVIEW

PEP_GVA_THICKSTDVIEW

PEP_GVA_BIRDSEYEVIEW

PEP_GVA_MAXVIEW


Graph Title Type Constants

Constant

PEP_GTT_TITLE

PEP_GTT_SUBTITLE

PEP_GTT_FOOTNOTE

PEP_GTT_SERIESTITLE

PEP_GTT_GROUPSTITLE

PEP_GTT_XAXISTITLE

PEP_GTT_YAXISTITLE

PEP_GTT_ZAXISTITLE


Graph Text Font Constants

Constant

PEP_GTF_TITLEFONT

PEP_GTF_SUBTITLEFONT

PEP_GTF_FOOTNOTEFONT

PEP_GTF_GROUPSTITLEFONT

PEP_GTF_DATATITLEFONT

PEP_GTF_LEGENDFONT

PEP_GTF_GROUPLABELSFONT

PEP_GTF_DATALABELSFONT


Graph Type and Subtype Constants

The following Graph Type and Subtype Constants are listed below.

Graph Major Type Constants

Bar Chart Subtype Constants

Line Chart Subtype Constants

Area Chart Subtype Constants

Pie Chart Subtype Constants

Doughnut Chart Subtype Constants

3D Riser Chart Subtype Constants

3D Surface Chart Subtype Constants

Scatter Chart Subtype Constants

Radar Chart Subtype Constants

Bubble Chart Subtype Constants

Stock (High/Low/Close) Chart Subtype Constants

Miscellaneous Chart Subtype Constants


Graph Major Type Constants

Constant | Description
PEP_GT_BARCHART |
PEP_GT_LINECHART |
PEP_GT_AREACHART |
PEP_GT_PIECHART |
PEP_GT_DOUGHNUTCHART |
PEP_GT_THREEDRISERCHART |
PEP_GT_THREEDSURFACECHART |
PEP_GT_SCATTERCHART |
PEP_GT_RADARCHART |
PEP_GT_BUBBLECHART |
PEP_GT_STOCKCHART |
PEP_GT_USERDEFINEDCHART | For PEGetGraphTypeInfo only.
PEP_GT_UNKNOWNTYPECHART | Do not use in PESetGraphTypeInfo.


Bar Chart Subtype Constants

Constant

PEP_GST_SIDEBYSIDEBARCHART

PEP_GST_STACKEDBARCHART

PEP_GST_PERCENTBARCHART

PEP_GST_FAKED3DSIDEBYSIDEBARCHART

PEP_GST_FAKED3DSTACKEDBARCHART

PEP_GST_FAKED3DPERCENTBARCHART


Line Chart Subtype Constants

Constant

PEP_GST_REGULARLINECHART

PEP_GST_STACKEDLINECHART

PEP_GST_PERCENTAGELINECHART

PEP_GST_LINECHARTWITHMARKERS

PEP_GST_STACKEDLINECHARTWITHMARKERS

PEP_GST_PERCENTAGELINECHARTWITHMARKERS


Area Chart Subtype Constants

Constant

PEP_GST_ABSOLUTEAREACHART

PEP_GST_STACKEDAREACHART

PEP_GST_PERCENTAREACHART

PEP_GST_FAKED3DABSOLUTEAREACHART

PEP_GST_FAKED3DSTACKEDAREACHART

PEP_GST_FAKED3DPERCENTAREACHART


Pie Chart Subtype Constants

Constant

PEP_GST_REGULARPIECHART

PEP_GST_FAKED3DREGULARPIECHART

PEP_GST_MULTIPLEPIECHART

PEP_GST_MULTIPLEPROPORTIONALPIECHART


Doughnut Chart Subtype Constants

Constant

PEP_GST_REGULARDOUGHNUTCHART

PEP_GST_MULTIPLEDOUGHNUTCHART

PEP_GST_MULTIPLEPROPORTIONALDOUGHNUTCHART


3D Riser Chart Subtype Constants

Constant

PEP_GST_THREEDREGULARCHART

PEP_GST_THREEDPYRAMIDCHART

PEP_GST_THREEDOCTAGONCHART

PEP_GST_THREEDCUTCORNERSCHART


3D Surface Chart Subtype Constants

Constant

PEP_GST_THREEDSURFACEREGULARCHART

PEP_GST_THREEDSURFACEWITHSIDESCHART

PEP_GST_THREEDSURFACEHONEYCOMBCHART


Scatter Chart Subtype Constants

Constant

PEP_GST_XYSCATTERCHART

PEP_GST_XYSCATTERDUALAXISCHART

PEP_GST_XYSCATTERWITHLABELSCHART

PEP_GST_XYSCATTERDUALAXISWITHLABELSCHART


Radar Chart Subtype Constants

Constant

PEP_GST_REGULARRADARCHART

PEP_GST_STACKEDRADARCHART

PEP_GST_RADARDUALAXISCHART


Bubble Chart Subtype Constants

Constant

PEP_GST_REGULARBUBBLECHART

PEP_GST_DUALAXISBUBBLECHART


Stock (High/Low/Close) Chart Subtype Constants

Constant

PEP_GST_HIGHLOWCHART

PEP_GST_HIGHLOWOPENCLOSECHART


Miscellaneous Chart Subtype Constants

Constant

PEP_GST_UNKNOWNSUBTYPECHART


Job Destination Constants

Constant

PEP_TO_NOWHERE

PEP_TO_WINDOW

PEP_TO_PRINTER

PEP_TO_EXPORT

PEP_FROM_QUERY


Job Status Constants

Job Status Constants are returned by CRPEJob::GetJobStatus, and by CRPEStopEventInfo, member jobStatus. CRPEJob::GetJobStatus will return -1 if the Crystal Report Engine has not been opened, or if a print job has not been established.

Constant | Description
PEP_JOBNOTSTARTED | The job has not been started.
PEP_JOBINPROGRESS | The job is currently in progress.
PEP_JOBCOMPLETED | The job has been completed successfully.
PEP_JOBFAILED | An error has occurred and the job has failed.
PEP_JOBCANCELLED | The job has been canceled by the user.
PEP_JOBHALTED | The job has too many records or has taken too much time.


Mouse Click Action Constants

Constant

PEP_MOUSE_NOTSUPPORTED

PEP_MOUSE_DOWN

PEP_MOUSE_UP

PEP_MOUSE_DOUBLE_CLICK


Report Prompt Option Constants

Constant | Value
PE_RPTOPT_PROMPT_NONE | 0
PE_RPTOPT_PROMPT_NORMAL | 1
PE_RPTOPT_PROMPT_ALWAYS | 2


Section Codes Constants

See Working with section codes.

Constant

PEP_ALLSECTIONS

PEP_SECT_REPORT_HEADER

PEP_SECT_PAGE_HEADER

PEP_SECT_GROUP_HEADER

PEP_SECT_DETAIL

PEP_SECT_GROUP_FOOTER

PEP_SECT_PAGE_FOOTER

PEP_SECT_REPORT_FOOTER


Sort Method Constants

Constant

PEP_OR_NO_SORT

PEP_OR_ALPHANUMERIC_ASCENDING

PEP_OR_ALPHANUMERIC_DESCENDING

PEP_OR_NUMERIC_ASCENDING

PEP_OR_NUMERIC_DESCENDING


Sort Order Constants

Constant | Description
PEP_SF_DESCENDING | Sorts data in descending order (Z to A, 9 to 1).
PEP_SF_ASCENDING | Sorts data in ascending order (A to Z, 1 to 9).


Subreport Info Constants

Constant | Value
PEP_SRI_ONOPENJOB | 0
PEP_SRI_ONFUNCTIONCALL | 1


Table Difference Constants

Any combination of Table Difference Constants can be returned from CRPEJob::CheckNthTableDifferences. The constants are used by CRPETableDifferenceInfo.

Constant | Value
PEP_TCD_OKAY | 0x00000000
PEP_TCD_DATABASENOTFOUND | 0x00000001
PEP_TCD_SERVERNOTFOUND | 0x00000002
PEP_TCD_SERVERNOTOPENED | 0x00000004
PEP_TCD_ALIASCHANGED | 0x00000008
PEP_TCD_INDEXESCHANGED | 0x00000010
PEP_TCD_DRIVERCHANGED | 0x00000020
PEP_TCD_DICTIONARYCHANGED | 0x00000040
PEP_TCD_FILETYPECHANGED | 0x00000080
PEP_TCD_RECORDSIZECHANGED | 0x00000100
PEP_TCD_ACCESSCHANGED | 0x00000200
PEP_TCD_PARAMETERSCHANGED | 0x00000400
PEP_TCD_LOCATIONCHANGED | 0x00000800
PEP_TCD_DATABASEOTHER | 0x00001000
PEP_TCD_NUMFIELDSCHANGED | 0x00010000
PEP_TCD_FIELDOTHER | 0x00020000
PEP_TCD_FIELDNAMECHANGED | 0x00040000
PEP_TCD_FIELDDESCCHANGED | 0x00080000
PEP_TCD_FIELDTYPECHANGED | 0x00100000
PEP_TCD_FIELDSIZECHANGED | 0x00200000
PEP_TCD_NATIVEFIELDTYPECHANGED | 0x00400000
PEP_TCD_NATIVEFIELDOFFSETCHANGED | 0x00800000
PEP_TCD_NATIVEFIELDSIZECHANGED | 0x01000000
PEP_TCD_FIELDDECPLACESCHANGED | 0x02000000


Zoom Constants

Constant | Description
PEP_ZOOM_FULL_SIZE | Full page.
PEP_ZOOM_SIZE_FIT_ONE_SIDE | Fit one side (highest magnification).
PEP_ZOOM_SIZE_FIT_BOTH_SIDES | Fit both sides.


class CRPEngine and class CRPEJob Obsolete Methods

This section describes the class CRPEngine and class CRPEJob obsolete methods. Documentation is provided for support of older applications. Use of these methods for new applications is not recommended.

CRPEJob::GetMinimumSectionHeight

CRPEJob::GetNParams

CRPEJob::GetNthParam

CRPEJob::GetNthParamInfo

CRPEJob::SetMinimumSectionHeight

CRPEJob::SetNthParam


CRPEJob::GetMinimumSectionHeight

CRPEJob::GetMinimumSectionHeight is obsolete. It will still work for older applications. However, there have been a number of major enhancements to the parameter fields (default values, multiple values, value ranges, etc.). Use CRPEJob::GetSectionHeight, for all new development.

CRPEJob::GetMinimumSectionHeight was used to retrieve the minimum section height information for selected sections in the specified report.

Syntax
BOOL GetMinimumSectionHeight (

            short sectionCode,

            short *height );
Parameters

sectionCode | Specifies the code for the report section for which you want to retrieve the minimum height. Use one of the PEP_XXX Section Codes Constants.
height | Specifies a pointer to the minimum height, in twips, for the specified report section.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::GetNParams

CRPEJob::GetNParams is now obsolete. It will still work for older applications. However, there have been a number of major enhancements to the parameter fields (default values, multiple values, value ranges, etc.). Use CRPEJob::GetNParameterFields, for all new development.

CRPEJob::GetNParams was used to determine how many parameters are required by a stored procedure in an SQL data base table. This method was usually used in conjunction with CRPEJob::GetNthParam, or CRPEJob::SetNthParam.

Syntax

short GetNParams ();

Returns
  • Returns the number of parameters in the current stored procedure being used to generate the report.
  • Returns -1 if an error occurs.


CRPEJob::GetNthParam

CRPEJob::GetNthParam is obsolete. It will still work for older applications. However, there have been a number of major enhancements to the parameter fields (default values, multiple values, value ranges, etc.). Use CRPEJob::GetNthParameterField, for all new development.

CRPEJob::GetNthParam was Used to determine a particular parameter required by a stored procedure in a SQL database table.

Syntax
BOOL GetNthParam (

        short paramN,

        CString &paramValue );
Parameters

paramN | Specifies which parameter in the stored procedure you want to retrieve. The first parameter of a stored procedure is 0, the second is 1, etc.
paramValue | Reference to the CString containing the current value of the specified parameter in the stored procedure.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

To determine whether a parameter field is a stored procedure, use CRPEJob::GetNthParameterField.


CRPEJob::GetNthParamInfo

CRPEJob::GetNthParamInfo is obsolete. It will still work for older applications. However, there have been a number of major enhancements to the parameter fields (default values, multiple values, value ranges, etc.). Use CRPEJob::GetParameterValueInfo, for all new development.

CRPEJob::GetNthParamInfo was used to retrieve the name and type of a specified stored procedure parameter.

Syntax
BOOL GetNthParamInfo (

        short paramN,

        CRPEParameterInfo *paramInfo );
Parameters

paramN | Specifies the number of the stored procedure parameter about which you want to retrieve information.
paramInfo | Specifies a pointer to an (obsolete) CRPEParameterInfo structure.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetMinimumSectionHeight

CRPEJob::SetMinimumSectionHeight is obsolete. It will still work for older applications. However, there have been a number of major enhancements to the parameter fields (default values, multiple values, value ranges, etc.). Use CRPEJob::SetSectionHeight, for all new development.

CRPEJob::SetMinimumSectionHeight was used to set the minimum section height information for selected sections in the specified report.

Syntax
BOOL SetMinimumSectionHeight (

        short sectionCode,

        short height );
Parameters

sectionCode | Specifies the section for which you want to specify the minimum height. Use one of the PEP_XXX Section Codes Constants.
height | Specifies the minimum height in twips of the specified section.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::SetNthParam

CRPEJob::SetNthParam is obsolete. It will still work for older applications. However, there have been a number of major enhancements to the parameter fields (default values, multiple values, value ranges, etc.). Use CRPEJob::SetNthParameterField, for all new development.

CRPEJob::SetNthParam was used to set the value of a parameter in a stored procedure.

Syntax
BOOL SetNthParam (

        short paramN,

        const char *paramValue );
Parameters

paramN | Specifies for which parameter in the stored procedure you want to set the value. The first parameter of a stored procedure is 0, the second is 1, etc.
paramValue | Specifies a pointer to the new value of the indicated parameter. This value must be a string. Please see Remarks below.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Remarks

All parameter values must be passed as string values. If you wish to pass a numeric value, pass the value in quotes (for example: "100").


class CRPEngine and class CRPEJob Obsolete Structures

This section describes the class CRPEngine and class CRPEJob obsolete structure. Documentation is provided for support of older applications. Use of this structure for new applications is not recommended.


CRPEParameterInfo

CRPEParameterInfo is obsolete. It will still work for older applications. However, there have been a number of major enhancements to the parameter fields (default values, multiple values, value ranges, etc.). Use CRPEParameterValueInfo, for all new development.

This structure was used to contains information about a parameter for a stored procedure in an SQL database. It was used by CRPEJob::GetNthParamInfo.

Data Members

m_Type | WORD | Specifies the data type of the parameter. Use the appropriate constant from the list below (these data types are supported by The Crystal Report Engine):
 | Data Type | Constant
 | Number | PEP_PF_NUMBER
 | Currency | PEP_PF_CURRENCY
 | Boolean | PEP_PF_BOOLEAN
 | Date | PEP_PF_DATE
 | String | PEP_PF_STRING
 | Date/Time | PEP_PF_DATETIME
 | Time | PEP_PF_TIME
m_Name | const _TCHAR | Specifies the name of the parameter in a null-terminated string.

Constructor CRPEParameterInfo::CRPEParameterInfo

This constructs an (obsolete) CRPEParameterInfo structure object. It assigns default values to the members of the structure.

Constructor Syntax

CRPEParameterInfo ();


Crystal Class Library for NewEra
Reference

The Crystal New Era Class Library is a wrapper around the Crystal Reports Engine API created specifically for programming in the Informix New Era development environment. In this section you will find detailed information on classes and their associated methods, and constants.

Click the appropriate link to jump to that section:

  • The Crystal NewEra Class Library
  • Other NewEra Classes
  • Class Constants


The Crystal NewEra Class Library

Introduction

The Crystal Class Library for NewEra is designed specifically for use with the Informix NewEra development environment. This class library is comprised of two primary classes and several supporting classes. These classes are wrapped around the Crystal Report Engine API and insulate the user from some of the details required to manage reports in an application.

The Crystal Class Library for NewEra was installed in the Crystal Informix directory (\CRW\INFORMIX by default) when you installed Crystal Reports. The header files (*.4GH) for the library are located in \CRW\INFORMIX\CLASS\INCL, while source files (*.4GL) are located in \CRW\INFORMIX\CLASS\SRC. Copy these files, along with CRPE.H, to the appropriate location for your NewEra application, then include CRYSTAL.4GH in the source file for your application project that will access the Crystal Report Engine.

Crystal Report Engine API

As mentioned above, the classes in the Crystal Class Library for NewEra are wrapped around the Crystal Report Engine API, and the methods in these classes make direct calls to the functions in the Crystal Report Engine API.

Classes in the Crystal Class Library for NewEra

The Crystal Class Library for NewEra consists of two primary classes. The class CRPEngine, is designed so that there should only be one CRPEngine object in the entire application. The CRPEngine object contains methods that are common to all print jobs (for example, SQL connections, version information, etc.). More importantly, it is responsible for creating and managing all class CRPEJob, objects. It is the CRPEJob object that allows you access to the attributes of a print job.


class CRPEngine

The CRPEngine class is designed so that there should only be one CRPEngine object in the entire application. The CRPEngine class contains methods that are common to all print jobs (that is, SQL connections, version information, etc.). More importantly, it is responsible for creating and managing all CRPEJob objects. It is the CRPEJob object that allows you access to the attributes of a print job.

In order to open a particular report it is first necessary to have an open Crystal Report Engine object in the application. You may then call CRPEngine::OpenJob, specifying the report file name to open. If successful, you will be returned a pointer to a CRPEJob object.


constructor CRPEngine::CRPEngine

This is the constructor for the class. If open is true, the actual Crystal Reports DLL is opened (crpe32.dll). Print jobs may only be opened if the engine itself is open. If originally opened with open = FALSE, the engine may be opened later with CRPEngine::Open.

Constructor Syntax

CRPEngine (v_open BOOLEAN : FALSE);

Parameter

v_open

Indicates whether or not the Crystal Report Engine should be opened when the CRPEngine object is created.


class CRPEngine Methods

The following methods are discussed in this section.

CRPEngine::CanClose

CRPEngine::Close

CRPEngine::GetEngineStatus

CRPEngine::GetErrorCode

CRPEngine::GetErrorText

CRPEngine::GetNPrintJobs

CRPEngine::GetVersion

CRPEngine::LogOffServer

CRPEngine::LogOnServer

CRPEngine::LogOnSQLServerWithPrivateInfo

CRPEngine::Open

CRPEngine::OpenJob

CRPEngine::PrintReport


CRPEngine::CanClose

Use CRPEngine::CanClose to Check to see whether or not the Crystal Report Engine is busy. Errors can occur in your application or on a system if you attempt to close the Crystal Report Engine while it is processing a print job. Use this method before attempting to close the Crystal Report Engine in an application (for example, when the user tries to exit) to determine if the Report Engine can be closed safely.

Syntax

CanClose () RETURNING BOOLEAN

Returns
  • TRUE if the Crystal Report Engine can be closed safely.
  • FALSE if the Crystal Report Engine is still busy.
Related Topics

CRPEngine::CanClose

PECanCloseEngine


CRPEngine::Close

This method closes the Crystal Report Engine.

Syntax

Close() RETURNING VOID

Related Topics

PECloseEngine


CRPEngine::GetEngineStatus

This method may be used to get the current engine status.

Syntax

GetEngineStatus() RETURNING SMALLINT

Returns

One of the following values of the Status enumerated type indicating the current status of the Crystal Report Engine.

Value | Description
engineOpen | The Crystal Report Engine is currently open.
engineClosed | The Crystal Report Engine has been closed, or is not yet open.
engineMissing | No Crystal Report Engine is available. Make sure the Crystal Report Engine DLL is located in a directory that appears in your PATH.


CRPEngine::GetErrorCode

This method returns the current error code of the Crystal Report Engine. When a call to another function fails, this call gets the error code that was generated so you can take some action based on that error code.

Syntax

GetErrorCode () RETURNING SMALLINT

Returns
  • Returns the current Crystal Report Engine Error Codes.
  • Returns 0 if no error has occurred.
Related Topics

PEGetErrorCode


CRPEngine::GetErrorText

This method returns a descriptive Crystal Report Engine error message.

Syntax

GetErrorText () RETURNING ixString

Returns

A ixString object containing the text for the current error code.

Related Topics

PEGetErrorText


CRPEngine::GetNPrintJobs

This method returns the number of print job (CRPEJob) objects that currently exist for the current CRPEngine object.

Syntax

GetNPrintJobs () RETURNING SMALLINT;

Returns
  • Returns the number of CRPEJob objects currently open.
  • Returns -1 if an error occurs.


CRPEngine::GetVersion

This method returns the version number of the Crystal Report Engine DLL (CRPE32.DLL) or the version of the Report Engine itself. The high-order byte is the major version number and the low-order byte is the minor version number.

This method can be used whenever you build functionality into a report that may not be available in earlier versions of the Crystal Report Engine and you need to verify the version number first. The function can be a handy safeguard for users who have more than one version of the Crystal Report Engine with the older version earlier in the path than the new version.

Syntax

GetVersion (versionRequested SMALLINT) RETURNING SMALLINT

Parameter

versionRequested

Specifies whether the version number of the Crystal Report Engine or the Report Engine DLL is being requested. Possible values are:

Value | Meaning
PEP_GV_DLL | Returns the version of the DLL.
PEP_GV_ENGINE | Returns the version of the Crystal Report Engine.

Returns

The version number of the currently used Crystal Report Engine or Report Engine DLL.

Related Topics

PEGetVersion


CRPEngine::LogOffServer

This method closes an existing connection to a SQL server. Connection information is provided through the class CRPELogOnInfo.

Syntax

LogOffServer(dllName CHAR (*), const CRPELogOnInfo logOnInfo) RETURNING BOOLEAN

Parameters

dllName | Specifies the name of the Crystal Reports DLL for the server or password protected non-SQL table you want to log on to.
logOnInfo | Specifies a pointer to a CRPELogOnInfo class.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PELogOffServer


CRPEngine::LogOnServer

This method opens a connection to a SQL server. More than one print job may use this connection to a SQL server. Information required to establish a connection is provided through the class CRPELogOnInfo.

Syntax

LogOnServer (dllName CHAR(*), logOnInfo CRPELogOnInfo) RETURNING BOOLEAN;

Parameters

dllName | Specifies the name of the Crystal Reports DLL for the server or password protected non-SQL table you want to log on to.
logOnInfo | Specifies a pointer to class CRPELogOnInfo.

Return Value
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PELogOnServer


CRPEngine::LogOnSQLServerWithPrivateInfo

Use this class method to allow the Crystal Report Engine to "piggyback" your application's existing connection to a Server. This lowers the number of connections established by a workstation, reducing application time and network traffic. It also prevents a LogOff call from disconnecting an application's existing connection to the Server. See Remarks below.

Syntax
LogOnSQLServerWithPrivateInfo (dllName CHAR (*), FOREIGN privateInfo)
RETURNING BOOLEAN
Parameters

dllName | Specifies the name of the Crystal Reports DLL that was used when establishing a connection to the Server when the report was first created. For example, if a report was created using an ODBC data source, specify the file name "PDSODBC.DLL". For more information on possible database DLLs, refer to Crystal Reports Developer Runtime Help (Runtime.hlp).
privateInfo | Specifies the application's handle to the Server connection. In your application, a connection to the Server must already be established before this method is called. Pass the HDBC (handle to a database connection) from this connection to the privateInfo parameter.

Remarks

The CRPEngine::LogOnSQLServerWithPrivateInfo method can only be used with database connections established by ODBC or Q+E Library 2.0. Any other database connections cannot be accessed by this method.

To obtain an HDBC for an ODBC connection, use the following function calls (see the ODBC SDK 2.0 manual for more information):

Function Call | Description
SQLAllocEnv | Initializes the ODBC call level interface and allocates memory for an environment handle.
SQLAllocConnect | Returns an ODBC HDBC. To obtain an HDBC for a Q+E Library connection, use the following function calls (see the InterSolv DataDirect Developer's Toolkit for more information).
qeConnect | Opens a connection to the server.
qeGetODBCHdbc | Returns the ODBC HDBC.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEngine::Open

This method opens the Crystal Report Engine. This method is only necessary if you constructed the CRPEngine object with the open parameter equal to FALSE. If you set the open parameter to TRUE when you constructed the CRPEngine object, this method is unnecessary.

Syntax

Open() RETURNING BOOLEAN

Returns
  • TRUE if the Crystal Report Engine was opened successfully.
  • FALSE if something went wrong.
Related Topics

constructor CRPEngine::CRPEngine

PEOpenEngine


CRPEngine::OpenJob

This method opens the report specified by reportFileName. A pointer to a CRPEJob object is returned. Print job attributes may be referenced through this object.

Syntax

OpenJob (reportFileName CHAR(*)) RETURNING CRPEJob

Parameter

reportFileName

The name and path (if necessary) of the report file being opened for the specified print job.

Returns

CRPEJob object for the opened print job.

Related Topics

PEOpenPrintJob


CRPEngine::PrintReport

This method provides a quick but limited way to print a report. The report may only be output to a printer or preview window. Use this class method any time you simply want to print a report from an application without giving the user the ability to customize the report.

Syntax
PrintReport (reportFilePath CHAR (*), toPrinter BOOLEAN : TRUE, toWindow
BOOLEAN : FALSE, title CHAR (*) : "Crystal Report", left SMALLINT : 0,top
SMALLINT : 0, width SMALLINT : 0, height SMALLINT : 0, style INTEGER : 0,
parentWindow ixWindow : NULL) RETURNING SMALLINT
Parameters

reportFilePath | Specifies the name and path of the report to be printed.
toPrinter | Specifies whether or not the report is to be sent to the default printer.
toWindow | Specifies whether or not the report is to be displayed in a preview window.
title | Specifies the title you want to appear in the title bar if the report is being sent to a preview window.
left | Specifies the x coordinate of the upper left hand corner of the preview window, in device coordinates.
top | Specifies the y coordinate of the upper left hand corner of the preview window, in device coordinates.
width | Specifies the width of the preview window, in device coordinates.
height | Specifies the height of the preview window, in device coordinates.
style | Specifies the style of the window being created. Style setting can be combined using the bitwise "OR" operator. Refer to the CWnd class in the Microsoft Foundation Class Library reference for possible window styles.
parentWindow | Specifies a pointer to the CWnd object for the window that is the parent of the preview window. Specify NULL if the preview window will not have a parent window.

Returns
  • Returns 0 if the call is successful.
  • Returns an error code if the call fails.
Related Topics

PEPrintReport


class CRPEJob

In order to open a particular report it is first necessary to have an open Crystal Report Engine object in the application. You may then call CRPEngine::OpenJob, specifying the report file name to open. If successful, you will be returned a pointer to a CRPEJob object. It is through this object that you may modify the print job attributes as well as output the report in various formats. Almost all of these methods correspond to similar functions available in the Crystal Report Engine API.

The class constructor is called automatically by CRPEngine::OpenJob ().


constructor CRPEJob::CRPEJob

This is the constructor for the class. It also stores the job number internally for future use in Crystal Report Engine API calls.

Note: This class constructor is automatically called by CRPEngine::OpenJob(). Do not call this constructor from within your own code.

Constructor Syntax

CRPEJob (jobHandle SMALLINT);

Parameter

jobHandle

Handle to the job created by CRPEngine::OpenJob().


class CRPEJob Methods

The following methods, listed alphabetically, are discussed in this section.

class CRPEJob Methods A - F

CRPEJob::Cancel

CRPEJob::CheckFormula

CRPEJob::CheckGroupSelectionFormula

CRPEJob::CheckSelectionFormula

CRPEJob::Close

CRPEJob::CloseWindow

CRPEJob::DeleteNthGroupSortField

CRPEJob::DeleteNthSortField

CRPEJob::ExportPrintWindow

CRPEJob::ExportTo

class CRPEJob Methods G (Get...)

CRPEJob::GetErrorCode

CRPEJob::GetErrorText

CRPEJob::GetExportOptions

CRPEJob::GetFormula

CRPEJob::GetGraphData

CRPEJob::GetGraphOptions

CRPEJob::GetGraphText

CRPEJob::GetGraphType

CRPEJob::GetGroupCondition

CRPEJob::GetGroupSelectionFormula

CRPEJob::GetJobHandle

CRPEJob::GetJobStatus

CRPEJob::GetLineHeight

CRPEJob::GetMargins

CRPEJob::GetMinimumSectionHeight

CRPEJob::GetNDetailCopies

CRPEJob::GetNFormulas

CRPEJob::GetNGroups

CRPEJob::GetNGroupSortFields

CRPEJob::GetNLinesInSection

CRPEJob::GetNParams

CRPEJob::GetNSortFields

CRPEJob::GetNTables

CRPEJob::GetNthFormula

CRPEJob::GetNthGroupSortField

CRPEJob::GetNthParam

CRPEJob::GetNthSortField

CRPEJob::GetNthTableLocation

CRPEJob::GetNthTableLogOnInfo

CRPEJob::GetNthTableSessionInfo

CRPEJob::GetNthTableType

CRPEJob::GetPrintDate

CRPEJob::GetPrintOptions

CRPEJob::GetReportTitle

CRPEJob::GetSectionFormat

CRPEJob::GetSelectedPrinter

CRPEJob::GetSelectionFormula

CRPEJob::GetSQLQuery

class CRPEJob Methods H - Z

CRPEJob::IsJobFinished

CRPEJob::NextWindowMagnification

CRPEJob::OutputToPrinter

CRPEJob::OutputToWindow

CRPEJob::PrintControlsShowing

CRPEJob::PrintWindow

CRPEJob::SelectPrinter

CRPEJob::SetFont

CRPEJob::SetFormula

CRPEJob::SetGraphData

CRPEJob::SetGraphOptions

CRPEJob::SetGraphText

CRPEJob::SetGraphType

CRPEJob::SetGroupCondition

CRPEJob::SetGroupSelectionFormula

CRPEJob::SetLineHeight

CRPEJob::SetMargins

CRPEJob::SetMinimumSectionHeight

CRPEJob::SetNDetailCopies

CRPEJob::SetNthGroupSortField

CRPEJob::SetNthParam

CRPEJob::SetNthSortField

CRPEJob::SetNthTableLocation

CRPEJob::SetNthTableLogOnInfo

CRPEJob::SetNthTableSessionInfo

CRPEJob::SetPrintDate

CRPEJob::SetPrintOptions

CRPEJob::SetReportTitle

CRPEJob::SetSectionFormat

CRPEJob::SetSelectionFormula

CRPEJob::SetSQLQuery

CRPEJob::Show...Page

CRPEJob::ShowPrintControls

CRPEJob::StartJob

CRPEJob::TestNthTableConnectivity

CRPEJob::ZoomPreviewWindow


CRPEJob::Cancel

Use Cancel to cancel processing of a print job. It can be tied to a control that allows the user to cancel a print job in progress.

Syntax

Cancel () RETURNING VOID

Related Topics

PECancelPrintJob


CRPEJob::CheckFormula

Use CheckFormula to check a named formula for errors. This method works just like the Check button in the Formula Editor. If the named formula contains an error, the method returns FALSE.

Syntax

CheckFormula (*formulaName CHAR (*)) RETURNING BOOLEAN

Parameter

formulaName

The name of the formula that you need to check for errors.

Returns
  • TRUE if the formula text is correct.
  • FALSE if there is an error in the formula or if the call fails.
Related Topics

PECheckFormula


CRPEJob::CheckGroupSelectionFormula

Use CheckGroupSelectionFormula to check the group selection formula for the report for errors. This method works just like the Check button in the Formula Editor. If the group selection formula contains an error, the method returns FALSE.

Syntax

CheckGroupSelectionFormula () RETURNING BOOLEAN

Returns
  • TRUE if the formula text is correct.
  • FALSE if there is an error in the formula or if the call fails.
Related Topics

PECheckGroupSelectionFormula


CRPEJob::CheckSelectionFormula

Use CheckSelectionFormula to check the record selection formula for the report for errors. This method works just like the Check button in the Formula Editor. If the selection formula contains an error, the method returns FALSE.

Syntax

CheckSelectionFormula () RETURNING BOOLEAN

Returns
  • TRUE if the formula text is correct.
  • FALSE if there is an error in the formula or if the call fails.
Related Topics

PECheckSelectionFormula


CRPEJob::Close

Use Close to close the print job. It also calls the destructor for the CRPEJob object. If printing has not yet finished when this method is called, it continues until the job is completely printed. If the preview window is open, it stays open.

Syntax

Close () RETURNING VOID

Related Topics

PEClosePrintJob


CRPEJob::CloseWindow

Use CloseWindow closes the preview window. If you are customizing preview window controls, implement this method to allow the user to close the preview window when finished viewing the report.

Syntax

CloseWindow () RETURNING VOID

Related Topics

PECloseWindow


CRPEJob::DeleteNthGroupSortField

Use DeleteNthGroupSortField to delete the group sort field at the specified position. The group and group summary are not removed from the report, but the field is removed from the list of group sort fields, and the summary data appearing in the group field is no longer sorted.

Syntax

DeleteNthGroupSortField (sortFieldN SMALLINT) RETURNING BOOLEAN

Parameter

sortFieldN

Specifies the 0-based number of the group sort field you want to delete. The first group sort field added to the report is field 0, the second is 1, etc.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PEDeleteNthGroupSortField


CRPEJob::DeleteNthSortField

Use DeleteNthSortField to delete the specified sort field from the report. The field is not deleted from the report, but it is removed from the list of sort fields, and data in that field no longer appears sorted.

Syntax

DeleteNthSortField (sortFieldN SMALLINT) RETURNING BOOLEAN

Parameter

sortFieldN

Specifies the number of the sort field you want to delete. The first sort field added to the report is field 0, the second is 1, etc.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PEDeleteNthSortField


CRPEJob::ExportPrintWindow

Use ExportPrintWindow to export the report displayed in the preview window to a disk file or e-mail address. If you are customizing preview window controls, use this method to enable the user to preview the report in the preview window, and if everything looks satisfactory, to export the report to a disk file or e-mail address (in response to a user event - button click, menu command, etc.).

Syntax

ExportPrintWindow (toMail BOOLEAN) RETURNING BOOLEAN

Parameter

toMail

Specifies whether or not the report file should be exported to an e-mail address. If TRUE, the file is exported to e-mail. If FALSE, the file is exported to a disk file.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.


CRPEJob::ExportTo

Use ExportTo to set the output of the print job to be exported. The export format is specified through the options parameter. This method does not export the report, but specifies that when the report is printed, it will be exported to a disk file or e-mail address according to settings in the options parameter. To actually export the report, use CRPEJob::StartJob.

Syntax

ExportTo (options CRPEExportOptions) RETURNING BOOLEAN

Parameter

options

Specifies a pointer to class CRPEExportOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PEExportTo


CRPEJob::GetErrorCode

Use GetErrorCode to retrieve the error code for the print job. When a call to another function fails, this call gets the error code that was generated so you can take some action based on that error code.

Syntax

GetErrorCode () RETURNING SMALLINT

Returns
  • Returns a Class Library Error Codes.
  • Returns PEP_NOERROR if no error has occurred.
Related Topics

PEGetErrorCode


CRPEJob::GetErrorText

Use GetErrorText to retrieve a descriptive error message for the print job.

Syntax

GetErrorText () RETURNING ixString

Returns

A ixString object containing the text for the current error.

Related Topics

PEGetErrorText


CRPEJob::GetExportOptions

Use GetExportOptions to prompt the user with a series of dialog boxes to specify the export options to be used. These options are used by the Class Library to fill in a class CRPEExportOptions. The CRPEJob::ExportTo, function can then be used to set the print job destination using the information in this class.

Syntax

GetExportOptions () RETURNING BOOLEAN, CRPEExportOptions

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

class CRPEExportOptions

Related Topics

PEGetExportOptions


CRPEJob::GetFormula

Use GetFormula to retrieve the formula text for the specified formula. CRPEJob::GetFormula is often used with CRPEJob::SetFormula, to identify and then change an existing formula in response to a user selection at print time.

Syntax

GetFormula (formulaName CHAR(*)) RETURNING BOOLEAN, ixString

Parameter

l

formulaName

The name of the formula for which you want to retrieve the formula string.

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

A ixString object containing the formula text.

Related Topics

PEGetFormula


CRPEJob::GetGraphData

Use GetGraphData to determine what data in your report is being used by a specified graph when the chart is created. This information includes which groups are used to create the rows and columns of the chart and which summary field in the report is used to set the values of the risers in the chart.

Syntax

GetGraphData (sectionCode SMALLINT, graphN SMALLINT) RETURNING BOOLEAN, CRPEGraphDataInfo

Parameters

sectionCode | Specifies the Section Codes, for the section of the report containing the chart from which you want to retrieve data.
graphN | Specifies from which chart within the section you want to retrieve chart data information. This value is 0-based. Within a section, charts are numbered from top to bottom first and from left to right if they have the same top.

Return Values

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

class CRPEGraphDataInfo

Related Topics

PEGetGraphTextInfo


CRPEJob::GetGraphOptions

Use GetGraphOptions to retrieve information about any of several chart options. These options include the minimum and maximum values that can appear on the chart, whether grid lines appear, whether risers are labeled, whether bar charts have horizontal or vertical bars, and whether a legend appears on the chart.

Syntax

GetGraphOptions (sectionCode SMALLINT, graphN SMALLINT) RETURNING BOOLEAN, CRPEGraphOptions

Parameters

sectionCode | Specifies the Section Codes, for the section of the report containing the chart from which you want to retrieve options.
graphN | Specifies from which chart within the section you want to retrieve chart options information. This value is 0-based. Within a section, charts are numbered from top to bottom first and from left to right if they have the same top.

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

class CRPEGraphOptions

Related Topics

PEGetGraphOptionInfo


CRPEJob::GetGraphText

Use GetGraphText to determine what text will appear with a chart. A chart can have a title, subtitle, footnote, title for groups, title for series, title for the X axis, title for the Y axis, and title for the Z axis (in 3D charts).

Syntax
GetGraphText (sectionCode SMALLINT, graphN SMALLINT) RETURNING BOOLEAN,
CRPEGraphTextInfo
Parameters

sectionCode | Specifies the Section Codes, for the section of the report containing the chart from which you want to retrieve text.
graphN | Specifies from which chart within the section you want to retrieve chart text information. This value is 0-based. Within a section, charts are numbered from top to bottom first and from left to right if they have the same top.

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

class CRPEGraphTextInfo

Related Topics

CRPEJob::GetGraphText

Seagate Software IMG Holdings, Inc.
http://www.seagatesoftware.com
Support services:
http://support.seagatesoftware.com


CRPEJob::GetGraphType

Use GetGraphType to retrieve which one of the available chart types is being used for the specified chart in the specified section. Use this method to find out what type of chart is being displayed in the report. There are many types of charts possible with Crystal Reports. This method will return the type of chart being displayed.

Syntax

GetGraphType (sectionCode SMALLINT, graphN SMALLINT) RETURNING BOOLEAN, SMALLINT

Parameters

sectionCode | Specifies the Section Codes, for the section of the report containing the chart from which you want to retrieve type information.
graphN | Specifies from which chart within the section you want to retrieve chart type information. This value is 0-based. Within a section, charts are numbered from top to bottom first and from left to right if they have the same top.

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

Chart Type Constants

Related Topics

PEGetGraphTypeInfo


CRPEJob::GetGroupCondition

Use GetGroupCondition to retrieve the group condition information for a selected group section in the specified report. Use this method to find out the group condition for a group section. Use CRPEJob::SetGroupCondition, to change the group condition once it is known.

Syntax
GetGroupCondition (sectionCode SMALLINT) RETURNING BOOLEAN, ixString,
SMALLINT, SMALLINT
Parameter

sectionCode

Specifies the Section Codes, for the section of the report for which you want to retrieve group condition information.

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

A ixString object containing the name of the group summary field.

A group condition field type constant which can be decoded using one of the following masks to separate the condition type from the group condition in the condition parameter.

  • PEP_GC_CONDITIONMASK: Obtains the group condition value. Use the bitwise AND (&) to combine this mask with the value of the condition parameter to obtain the group condition value.
  • PEP_GC_TYPEMASK: Obtains the type of field used for the group condition. Use the bitwise AND (&) to combine this mask with the value of the condition parameter to obtain a value representing the type of field used by the group condition.

A Sort Order Constants.

Remarks

For group condition field types other than Date and Boolean, the group condition value of the condition parameter is PEP_GC_ANYCHANGE.

Value (Date Fields) | Meaning
PEP_GC_DAILY | Triggers a grouping every time the date changes.
PEP_GC_WEEKLY | Triggers a grouping every time the date changes from one week to the next (a week runs from Sunday through Saturday).
PEP_GC_BIWEEKLY | Triggers a grouping every time the date changes from one two-week period to the next.
PEP_GC_SEMIMONTHLY | Triggers a grouping every time the date changes from one half-month period to the next.
PEP_GC_MONTHLY | Triggers a grouping every time the date changes from one month to the next.
PEP_GC_QUARTERLY | Triggers a grouping every time the date changes from one calendar quarter to the next.
PEP_GC_SEMIANNUALLY | Triggers a grouping every time the date changes from one half-year period to the next.
PEP_GC_ANNUALLY | Triggers a grouping every time the date changes from one year to the next.
Value (Boolean Fields) | Meaning
PEP_GC_TOYES | Triggers a grouping every time the sort and group by field changes from No to Yes.
PEP_GC_TONO | Triggers a grouping every time the sort and group by field changes from Yes to No.
PEP_GC_EVERYYES | Triggers a grouping every time the group and sort by field value is Yes.
PEP_GC_EVERYNO | Triggers a grouping every time the group and sort by field value is No.
PEP_GC_NEXTISYES | Triggers a grouping every time the next value in the sort and group by field is Yes.
PEP_GC_NEXTISNO | Triggers a grouping every time the next value in the sort and group by field is No.

The group condition field type portion of the condition parameter will be one of the following values:

Value | Meaning
PEP_GC_TYPEOTHER | Any field type other than Date or Boolean. The group condition portion of the condition parameter will be PEP_GC_ANYCHANGE.
PEP_GC_TYPEDATE | A Date field is used to create the group summary field.
PEP_GC_TYPEBOOLEAN | A Boolean field is used to create the group summary field.

Related Topics

PEGetGroupCondition


CRPEJob::GetGroupSelectionFormula

Syntax

GetGroupSelectionFormula () RETURNING BOOLEAN, ixString

Remarks

This method returns the formula text for the group selection formula. CRPEJob::GetGroupSelectionFormula is often used with CRPEJob::SetGroupSelectionFormula, to identify and then change an existing group selection formula at print time in response to a user selection.

Return Value

BOOLEAN | TRUE if the call is successful, FALSE if something goes wrong.
ixString | Specifies the existing group selection formula for the report.

Related Topics

PEGetGroupSelectionFormula


CRPEJob::GetJobHandle

Syntax

GetJobHandle () RETURNING SMALLINT

Remarks

This method returns the job handle for the print job.

Return Value

The print job handle for the CRPEJob object.


CRPEJob::GetJobStatus

Syntax

GetJobStatus () RETURNING SMALLINT, CRPEJobInfo

Remarks

This method gets the current status of the print job. You can use it in a number of programming situations, for example:

  • to trigger error messages, (when a print job fails due to insufficient memory, insufficient disk space, etc.),
  • to trigger screen displays (hourglass, series of graphics, etc.) that confirm to the user that work is in progress, or
  • to find out whether a job was cancelled by the user after CRPEJob::StartJob was called.
Return Values

SMALLINT

Returns one of the following values according to the status of the current print job:

Value | Meaning
-1 | The Crystal Report Engine has not been opened, or a print job has not been established.
PEP_JOBNOTSTARTED | The job has not been started.
PEP_JOBINPROGRESS | The job is currently in progress.
PEP_JOBCOMPLETED | The job has completed successfully.
PEP_JOBFAILED | The job has failed.
PEP_JOBCANCELLED | The job has been cancelled by the user.

CRPEJobInfo

Class CRPEJobInfo.

Related Topics

PEGetJobStatus


CRPEJob::GetLineHeight

Syntax
GetLineHeight (sectionCode SMALLINT, lineN SMALLINT) RETURNING BOOLEAN,
SMALLINT, SMALLINT
Parameters

sectionCode | Specifies the Section Codes, for the section of the report for which you want to retrieve line height.
lineN | Specifies the 0-based line number within the specified section for which you want to retrieve the height. The first line in a section is line 0, the second is 1, etc. Use PEP_ALLLINES to retrieve information on all lines in a section.

Remarks

Gets line height and ascent information for a specified line in a selected section of the report. You can change and pass back a new line height and ascent using CRPEJob::SetLineHeight.

Return Value

BOOLEAN | TRUE if the call is successful, FALSE if something goes wrong.
SMALLINT | Retrieves the height, in twips, of the specified line.
SMALLINT | Retrieves the line ascent, in twips, of the specified line. Line ascent is the distance from the baseline of the font to the top of the line space.


CRPEJob::GetMargins

Syntax

GetMargins () RETURNING BOOLEAN, SMALLINT, SMALLINT, SMALLINT, SMALLINT

Remarks

Retrieves the page margin settings for the specified report. Use this method to find out what the currently set margins for the report are. Use CRPEJob::SetMargins, to change report margins.

Return Value

BOOLEAN | TRUE if the call is successful, FALSE if something goes wrong.
SMALLINT | Retrieves the current setting of the left margin in twips.
SMALLINT | Retrieves the current setting of the right margin in twips.
SMALLINT | Retrieves the current setting of the top margin in twips.
SMALLINT | Retrieves the current setting of the bottom margin in twips.

Related Topics

PEGetMargins


CRPEJob::GetMinimumSectionHeight

Syntax

GetMinimumSectionHeight (sectionCode SMALLINT) RETURNING BOOLEAN, SMALLINT

Parameter

sectionCode

Specifies the Section Codes, for the section of the report for which you want to retrieve minimum section height.

Remarks

Retrieves minimum section height information for selected sections in the specified report. Use this method to fetch the minimum section height and pass back using CRPEJob::SetMinimumSectionHeight.

Return Values

BOOLEAN | TRUE if the call is successful, FALSE if something goes wrong.
SMALLINT | Retrieves the minimum height, in twips, for the specified report section.


CRPEJob::GetNDetailCopies

Syntax

GetNDetailCopies () RETURNING BOOLEAN, SMALLINT

Remarks

Returns the number of copies of each Details section in the report that are to be printed. Use this method to find out how many times each Details section of the report will be printed. To change the number of times each Details section is printed, use CRPEJob::SetNDetailCopies.

Return Values

BOOLEAN | TRUE if the call is successful, FALSE if something goes wrong.
nCopies | Retrieves the current setting for the number of times the Details section of the report will be printed.

Related Topics

PEGetNDetailCopies


CRPEJob::GetNFormulas

Syntax

GetNFormulas () RETURNING SMALLINT

Remarks

Use this function to fetch the number of formulas in the report. To fetch the formula by number, use CRPEJob::GetNthFormula.

Return Value

The number of formulas in the report. If no formulas exist in the report, 0 is returned. If an error occurs, -1 is returned.

Related Topics

PEGetNFormulas


CRPEJob::GetNGroups

Use GetNGroups to retrieve the number of group sections in the report.

Syntax

GetNGroups () RETURNING SMALLINT

Returns
  • Returns the number of group sections in the report.
  • Returns -1 if an error occurs.
Related Topics

PEGetNGroups


CRPEJob::GetNGroupSortFields

Use GetNGroupSortFields to retrieve the number of group sort fields in the specified report. This method is typically used as one of a series: GetNGroupSortFields (called once); CRPEJob::GetNthSortField, (called as many times as needed to identify the correct group sort field); and CRPEJob::SetNthSortField, (called once when the correct group sort field is identified). The series can be used to identify and then change an existing group sort field and/or sort order at print time in response to a user selection.

Syntax

GetNGroupSortFields () RETURNING SMALLINT

Returns
  • Returns the number of group sort fields in the report.
  • Returns 0 if there are no group sort fields.
  • Returns -1 if an error occurs.
Related Topics

PEGetNGroupSortFields


CRPEJob::GetNLinesInSection

Use this method to determine the number of lines in the specified section of the report, that is, how long a specified report section is according to the number of lines. For example, this is useful when trying to fit mailing label reports into the labels you are using.

Syntax

GetNLinesInSection (sectionCode SMALLINT) RETURNING SMALLINT

Parameter

sectionCode

Specifies the Section Codes, for the section of the report for which you want to retrieve the number of lines.

Returns
  • Returns the number of lines in the specified section of the report.
  • Returns -1 if an error occurs.


CRPEJob::GetNParams

Syntax

GetNParams () RETURNING SMALLINT

Remarks

Use this method whenever you need to know how many parameters are required by a stored procedure in a SQL database table. This method is usually used in conjunction with CRPEJob::GetNthParam, or CRPEJob::SetNthParam.

Return Value

The number of parameters in the current stored procedure being used to generate the report.

Related Topics

PEGetNParameterFields


CRPEJob::GetNSortFields

Syntax

GetNSortFields () RETURNING SMALLINT

Remarks

This method gets the number of sort fields in the report.

Return Value

The number of sort fields defined in the report. Returns 0 (zero) if there are no sort fields in the report. Returns -1 if an error occurs.

Related Topics

PEGetNSortFields


CRPEJob::GetNTables

Syntax

GetNTables() RETURNING SMALLINT

Remarks

This method returns the number of tables in the report.

Return Value

The number of tables used in the report. Returns -1 if an error occurs.


CRPEJob::GetNthFormula

Syntax

GetNthFormula (formulaN SMALLINT) RETURNING BOOLEAN, ixString, ixString

Parameter

formulaN

Specifies the 0-based number of the formula about which you want to gather information. The first formula added to your report is 0, the second is 1, etc.

Remarks

Use this function to obtain the formula name and formula text of a specific formula in the report. Once the formula name is obtained, formula text can be changed with CRPEJob::SetFormula.

Return Values

BOOLEAN | TRUE if the call is successful, FALSE if something goes wrong.
ixString | Retrieves the name of the formula specified.
ixString | Retrieves the text of the formula specified.

Related Topics

PEGetNthFormula


CRPEJob::GetNthGroupSortField

Syntax

GetNthGroupSortField (sortFieldN SMALLINT) RETURNING BOOLEAN, ixString, SMALLINT

Parameter

sortFieldN

Specifies the 0-based number of the group sort field you want to retrieve. The first group sort field is field 0. If the report has N sort fields, the function can be called with sortFieldN between 0 and N-1.

Remarks

Returns information about one of the group sort fields in the specified report: that is, it returns the name of the field and the direction (ascending or descending) of the sort. This method is typically used as one of a series: CRPEJob::GetNGroupSortFields (called once), CRPEJob::GetNthGroupSortField (called as many times as needed to identify the correct group sort field), and CRPEJob::SetNthGroupSortField (called once when the correct sort field is identified). The series can be used to identify and then change an existing group sort field and/or sort order at print time in response to a user selection.

Returns

BOOLEAN | TRUE if the call is successful, FALSE if something goes wrong.
ixString | Retrieves the name of the group sort field.
SMALLINT | Retrieves one of the Sort Order Constants.

Related Topics

PEGetNthGroupSortField


CRPEJob::GetNthParam

Syntax

GetNthParam (paramN SMALLINT) RETURNING BOOLEAN, ixString

Parameter

paramN

Specifies which parameter in the stored procedure you want to get the value of. The first parameter of a stored procedure is 0, the second is 1, etc.

Remarks

Gets the Nth parameter of a stored procedure. Use this method whenever you need to find out a particular parameter required by a stored procedure in a SQL database table.

Returns

BOOLEAN | TRUE if the call is successful, FALSE if something goes wrong.
ixString | Retrieves the current value of the specified parameter in the stored procedure.

Related Topics

PEGetNthParameterCurrentValue


CRPEJob::GetNthSortField

Syntax

GetNthSortField (sortFieldN SMALLINT) RETURNING BOOLEAN, ixString, SMALLINT

Parameter

sortFieldN

Specifies the number of the sort field you want to retrieve. The first sort field added to the report is field 0, the second is 1, etc.

Remarks

This method gets the name of the sort field at the specified sort field position and the direction in which data is sorted (ascending or descending).

Returns

BOOLEAN | TRUE if the call is successful, FALSE if something goes wrong.
ixString | Assigned the name of the sort field if the call completes successfully.
SMALLINT | Retrieves one of the Sort Order Constants.

Related Topics

PEGetNthSortField


CRPEJob::GetNthTableLocation

Use GetNthTableLocation to retrieve the table location information for the specified table in the report. This method is typically combined with CRPEJob::SetNthTableLocation, to identify the location of a table and then to change it.

Syntax

GetNthTableLocation (tableN SMALLINT) RETURNING BOOLEAN, CRPETableLocation

Parameter

tableN

Specifies the 0-based number of the table for which you want to retrieve location information.

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

class CRPETableLocation

Related Topics

PEGetNthTableLocation


CRPEJob::GetNthTableLogOnInfo

Use GetNthTableLogOnInfo to retrieve SQL connection information for the specified table.

Syntax

GetNthTableLogonInfo (tableN SMALLINT) RETURNING BOOLEAN, CRPELogonInfo

Parameter

tableN

Specifies the 0-based number of the table from which you want to get log on information.

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

class CRPELogOnInfo

Related Topics

PEGetNthTableLogOnInfo


CRPEJob::GetNthTableSessionInfo

Use GetNthTableSessionInfo to retrieve the session information for the specified Microsoft Access table. Many MS Access database tables require that a session be opened before the information in the table can be used. Use this method to obtain the session information (User ID and Session Handle) for a particular tab.

Syntax

GetNthTableSessionInfo (tableN SMALLINT) RETURNING BOOLEAN, CRPESessionInfo

Parameter

tableN

A 0-based table number indicating for which MS Access table in the report you want to obtain the session information.

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

class CRPESessionInfo

Related Topics

PEGetNthTableSessionInfo


CRPEJob::GetNthTableType

Use GetNthTableType to retrieve the table type information for the specified table.

Syntax

GetNthTableType (tableN SMALLINT) RETURNING BOOLEAN, CRPETableType

Parameter

tableN

The 0-based table number indicating for which table in the report you want to determine the type.

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

class CRPETableType

Related Topics

PEGetNthTableType


CRPEJob::GetPrintDate

Use GetPrintDate to retrieve the print date (if any) that was specified with the report. Use this method to retrieve the print date and pass it back using CRPEJob::SetPrintDate.

Syntax

GetPrintDate () RETURNING BOOLEAN, SMALLINT, SMALLINT, SMALLINT

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

The year component of the current print date.

The month component of the current print date.

The day component of the current print date.

Related Topics

PEGetPrintDate


CRPEJob::GetPrintOptions

Use GetPrintOptions to retrieve the print options specified for the report (the options that are set in the Print Setup common dialog box) and use them to fill in the class CRPEPrintOptions. Use this function to retrieve print options from the report in order to update them and pass back using CRPEJob::SetPrintOptions.

Syntax

GetPrintOptions () RETURNING BOOLEAN, CRPEPrintOptions

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

class CRPEPrintOptions.

Related Topics

PEGetPrintOptions


CRPEJob::GetReportTitle

Use GetReportTitle to retrieve the report title for the print job.

Syntax

GetReportTitle () RETURNING BOOLEAN, ixString

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

A ixString object containing the report title.

Related Topics

PEGetReportTitle


CRPEJob::GetSectionFormat

Use GetSectionFormat to retrieve the section format settings for a selected section in the specified report and supply the information by assigning values to the members of class CRPESectionOptions. Use this method in order to edit and update the section formats and pass the information back using CRPEJob::SetSectionFormat.

Syntax

GetSectionFormat (sectionCode SMALLINT) RETURNING BOOLEAN, CRPESectionOptions

Parameter

sectionCode

Specifies the Section Codes, for the section of the report for which you want to retrieve format information.

Returns

Boolean

  • TRUE if the call is successful.
  • FALSE if the call fails.

class CRPESectionOptions.

Related Topics

PEGetSectionFormat


CRPEJob::GetSelectedPrinter

Syntax

GetSelectedPrinter () RETURNING BOOLEAN, ixString, ixString, ixString, FOREIGN

Remarks

If a non-default printer is specified in the report, this method retrieves information about that printer. If you need to know which printer has been specified with the report, use CRPEJob::GetSelectedPrinter to obtain the information. This can be useful to determine if the user has access to the printer specified in the report and to choose another printer if not.

Returns

BOOLEAN | TRUE if the call is successful, FALSE if something goes wrong.
ixString | Retrieves the name of the printer driver for the currently selected printer in the report.
ixString | Retrieves the name of the printer currently selected in the report.
ixString | Retrieves the name of the port the currently selected printer is attached to. For example, "LPT1:".
FOREIGN | A DEVMODE class that contains information on the currently selected printer, if the CRPEJob::GetSelectedPrinter method completes successfully. For more information, see DEVMODE.

Related Topics

PEGetSelectedPrinter


CRPEJob::GetSelectionFormula

Syntax

GetSelectionFormula() RETURNING BOOLEAN, ixString

Remarks

This method returns the formula text for the record selection formula. CRPEJob::GetSelectionFormula is often used with CRPEJob::GetSelectionFormula, to identify and then change an existing selection formula at print time in response to a user selection.

Returns

BOOLEAN | TRUE if the call is successful, FALSE if something goes wrong.
ixString | Specifies the existing selection formula for the report.

Related Topics

PEGetSelectionFormula


CRPEJob::GetSQLQuery

Syntax

GetSQLQuery () RETURNING BOOLEAN, ixString

Remarks

This method retrieves the sql query that will be sent to the database server. This method can be used withCRPEJob::SetSQLQuery to retrieve and then change the SQL query for the report.

Return Values

TRUE if the call is successful, FALSE if something goes wrong.

ixString

Assigned the text of the SQL query being sent to the server if the call completes successfully.

Related Topics

PEGetSQLQuery


CRPEJob::IsJobFinished

Syntax

IsJobFinished () RETURNING BOOLELAN

Remarks

This method returns a Boolean value that indicates whether or not processing has finished for the print job. You can use this method any time you have a call that is contingent on a print job being finished.

Return Value

TRUE if processing has finished, FALSE if the job is in progress.

Related Topics

PEIsPrintJobFinished


CRPEJob::NextWindowMagnification

Syntax

NextWindowMagnification () RETURNING BOOLEAN

Remarks

This method switches to the next preview window magnification in order. Use this function to cycle through the three levels of preview window magnification whenever the report has been printed to a preview window. The three levels of magnification are: Full Page, Fit One Side, and Fit Both Sides.

Return Value

TRUE if the call is successful, FALSE if something goes wrong.

Related Topics

PENextPrintWindowMagnification


CRPEJob::OutputToPrinter

Use OutputToPrinter to set the output of the print job to the printer with the specified number of copies. This method does not print the report, but specifies that when the report is printed, it will be sent to a printer. To actually print the report, use CRPEJob::StartJob.

Syntax

OutputToPrinter (nCopies SMALLINT : 1) RETURNING BOOLEAN

Parameter

nCopies

Specifies how many copies of the report are to be printed. Default is 1 copy.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PEOutputToPrinter


CRPEJob::OutputToWindow

Use OutputToWindow to set the output of the print job to the preview window which will have the specified attributes. This method does not print the report to the window, but specifies that when the report is printed, it will appear in a preview window. To actually print the report, use CRPEJob::StartJob.

Syntax
OutputToWindow (title CHAR (*), left SMALLINT, top SMALLINT, width
SMALLINT, height SMALLINT, style INTEGER, parentWindow ixWindow)
RETURNING BOOLEAN
Parameters

title | Specifies the title that you want to appear in the title bar.
left | Specifies the x coordinate of the upper left hand corner of the preview window, in device coordinates.
top | Specifies the y coordinate of the upper left hand corner of the preview window, in device coordinates.
width | Specifies the width of the preview window, in device coordinates.
height | Specifies the height of the preview window, in device coordinates.
style | Specifies the style of the window being created. Style setting can be combined using the bitwise Or operator ( | ). Refer to the CWnd class in the Microsoft Foundation Class Library reference for possible window styles.
parentWindow | Specifies a pointer to the CWnd object for the window that is the parent of the preview window. Specify NULL if the preview window will not have a parent window.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PEOutputToWindow


CRPEJob::PrintControlsShowing

Syntax

PrintControlsShowing () RETURNING BOOLEAN, SMALLINT

Remarks

Checks if the print controls are displayed in the preview window. Use CRPEJob::ShowPrintControls, to change whether or not print controls will appear in the preview window.

Returns

BOOLEAN | TRUE if the call is successful, FALSE if something goes wrong.
SMALLINT | Returns a pointer to a TRUE value if the print controls will be shown in the preview window, FALSE if they will be hidden.

Related Topics

PEPrintControlsShowing


CRPEJob::PrintWindow

Syntax

PrintWindow () RETURNING BOOLEAN

Remarks

This method prints the report displayed in the preview window to the printer. If you are customizing preview window controls, use this method to enable the user to preview the report in the preview window, and then, if everything looks satisfactory, to print the report to the printer (in response to a user event - button click, menu command, etc.).

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PEPrintWindow


CRPEJob::SelectPrinter

Syntax
SelectPrinter (driverName CHAR (*), printerName CHAR (*), portName CHAR
(*), mode FOREIGN) RETURNING BOOLEAN
Parameters

driverName | Specifies the name of the printer driver for the printer being selected.
printerName | Specifies the name of the printer being selected (as indicated in the Printers Control Panel).
PortName | Specifies the name of the port the printer is attached to. For example: "LPT1:".
mode | A pointer to a DEVMODE class. The default implementation of CRPEJob::SelectPrinter ignores this parameter. For more information, see DEVMODE.

Remarks

This method specifies the printer and/or print characteristics for the print job. You can use this method to enable the user to select a printer other than the default printer at print time. One way of doing this is to have your application call the Windows common Print Setup dialog box.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetPrintDate


CRPEJob::SetFont

Syntax
SetFont (sectionCode SMALLINT, scopeCode SMALLINT, faceName CHAR (*),
fontFamily SMALLINT, fontPitch SMALLINT, charSet SMALLINT, pointSize
SMALLINT, isItalic SMALLINT, isUnderlined SMALLINT, isStruckOut
SMALLINT, weight SMALLINT) RETURNING BOOLEAN
Parameters

sectionCode

Specifies the section of the report for which you want to set the font. Use one of the following values:

Value | Meaning
PEP_ALLSECTIONS | Sets the line height for all sections.
PEP_HEADERSECTION | Sets the line height for the Page Header section.
PEP_GROUPHEADER | Sets the line height for the Group Header section.
PEP_DETAILSECTION | Sets the line height for the Details section.
PEP_GROUPFOOTER | Sets the line height for the Group Footer section.
PEP_GRANDTOTALSECTION | Sets the line height for the Grand Total section.
PEP_FOOTERSECTION | Sets the line height for the Page Footer section.

scopeCode

Specifies whether the font selected is to apply to fields, to text, or to both. To specify both, use the bitwise Or operator: |. The following values are possible:

Value | Meaning
PEP_FIELDS | Sets the default font for fields in the report section specified.
PEP_TEXT | Sets the default font for all text (that has not been entered as a text field value) in the report section specified.
faceName | Specifies the actual face name of the font you want to use. The face name you pass can typically come from a font dialog box, be hard coded in the application, or be chosen by the application from the fonts supported on the printer. For example: "Times New Roman".
fontFamily | Specifies the font family for the font you want to use. Use one of the following values:
Value | Meaning
FF_DONTCARE | No font family or family does not matter.
FF_ROMAN | Variable pitch font with serifs.
FF_SWISS | Fixed pitch font without serifs.
FF_MODERN | Fixed pitch font, with or without serifs.
FF_SCRIPT | Handwriting-like font.
FF_DECORATIVE | Fancy display font.

fontPitch

Specifies the font pitch you wish to use. Use one of the following values:

Value | Meaning
DEFAULT_PITCH | Retains the default pitch for the font.
FIXED_PITCH | Fixed pitch, each character is the same width.
VARIABLE_PITCH | Variable pitch, the width of each character varies.

charSet

Specifies the character set you wish to use. Use one of the following values:

Value

ANSI_CHARSET

DEFAULT_CHARSET

SYMBOL_CHARSET

HANGEFUL_CHARSET

OEM_CHARSET

SHIFTJIS_CHARSET

CHINESEBIG5_CHARSET

pointSize | Specifies the desired point size for the selected font. Use 0 to indicate no change.
isItalic | Specifies whether the font selected should be italicized. Use 1 for italics, 0 for no italics, or PEP_UNCHANGED to leave the italics as set up in the report.
isUnderlined | Specifies whether the font should be underlined. Use 1 to underline, 0 for no underline, or PEP_UNCHANGED to leave underline settings as specified in the report.
isStruckOut | Specifies whether or not the font should appear in strikethrough format. Use 1 for strike-out, 0 for no strike out, or PEP_UNCHANGE to leave strike-out settings as specified in the report.
weight | Specifies the weight of the font. Possible values are:
Value

FW_DONTCARE

FW_EXTRALIGHT

FW_NORMAL

FW_SEMIBOLD

FW_EXTRABOLD

FW_ULTRALIGHT

FW_DEMIBOLD

FW_BLACK

FW_THIN

FW_LIGHT

FW_MEDIUM

FW_BOLD

FW_HEAVY

FW_REGULAR

FW_ULTRABOLD

Remarks

This method sets the font and font characteristics for the specified section. Use any time you need to change a default font at runtime in response to user input, or to specify a built-in printer font.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetFont


CRPEJob::SetFormula

Syntax

SetFormula (formulaName CHAR(*), formulaText CHAR(*)) RETURNING BOOLEAN

Parameters

formulaName | The name of the formula for which you want to assign new formula text.
formulaText | The actual formula text that replaces the existing formula string.

Remarks

This method sets the formula text for the specified formula. CRPEJob::SetFormula is often used with CRPEJob::GetFormula, to identify and then change an existing formula at print time in response to a user selection.

Returns
  • TRUE if the call is successful.
  • FALSE there is an error in the formula, or if the call fails.
Related Topics

PESetFormula


CRPEJob::SetGraphData

Use SetGraphData to change the data that is used from your report to create a specified chart. This information includes the groups used to create the rows and columns of the chart and the summary field used to set the values of the risers in the chart.

Syntax
SetGraphData (sectionCode SMALLINT, graphN SMALLINT, graphDataInfo
CRPEGraphDataInfo) RETURNING BOOLEAN
Parameters

sectionCode | Specifies the Section Codes, for the section of the report containing the chart for which you want to set data information.
graphN | Specifies from which chart within the section you want to set chart data information. This value is 0-based. Within a section, charts are numbered from top to bottom first and from left to right if they have the same top.
graphDataInfo | Specifies a pointer to class CRPEGraphDataInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetGraphTextInfo


CRPEJob::SetGraphOptions

Use SetGraphOptions to change any of several chart options. These options include the minimum and maximum values that can appear on the chart, whether grid lines appear, whether risers are labeled, whether bar charts have horizontal or vertical bars, and whether a legend appears on the chart.

Syntax
SetGraphOptions (sectionCode SMALLINT, graphN SMALLINT, graphOptions
CRPEGraphOptions) RETURNING BOOLEAN
Parameters

sectionCode | Specifies the Section Codes, for the section of the report containing the chart for which you want to set options information.
graphN | Specifies from which chart within the section you want to set chart options information. This value is 0-based. Within a section, charts are numbered from top to bottom first and from left to right if they have the same top.
graphOptions | Specifies a pointer to class CRPEGraphOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetGraphOptionInfo


CRPEJob::SetGraphText

Use SetGraphText to set or change the text that appears with a chart. A chart can have a title, subtitle, footnote, title for groups, title for series, title for the X axis, title for the Y axis, and title for the Z axis (in 3D chart).

Syntax
SetGraphText (sectionCode SMALLINT, graphN SMALLINT, graphTextInfo
CRPEGraphTextInfo) RETURNING BOOLEAN
Parameters

sectionCode | Specifies the Section Codes, for the section of the report containing the chart for which you want to set text information.
graphN | Specifies from which chart within the section you want to set chart text information. This value is 0-based. Within a section, charts are numbered from top to bottom first and from left to right if they have the same top.
graphTextInfo | Specifies a pointer to class CRPEGraphTextInfo.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetGraphTextInfo


CRPEJob::SetGraphType

Use SetGraphType to set the type of chart displayed for the specified chart in the specified section based on one of the available types. Use this method to change the type of chart that is displayed in a report.

Syntax
SetGraphType (sectionCode SMALLINT, graphN SMALLINT, graphType SMALLINT)
RETURNING BOOLEAN
Parameters

sectionCode | Specifies the Section Codes, for the section of the report containing the chart for which you want to set type information.
graphN | Specifies from which chart within the section you want to set chart type information. This value is 0-based. Within a section, charts are numbered from top to bottom first and from left to right if they have the same top.
graphType | Specifies one of the Chart Type Constants, indicating the style of the chart that you want to set.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetGraphTypeInfo


CRPEJob::SetGroupCondition

Syntax

SetGroupCondition (sectionCode SMALLINT,conditionField CHAR(*), condition SMALLINT, sortDirection SMALLINT) RETURNING BOOLEAN

Parameters

sectionCode | Specifies the Section Codes, for the section of the report for which you want to set group condition information.
conditionField | Specifies the field that triggers a summary whenever its value changes. Use the name of the field as indicated in the report file.
condition | Specifies the condition that needs to be met for Date and Boolean fields. For all field types except Date and Boolean, use PEP_GC_ANYCHANGE as the condition parameter.
Value (Date Fields) | Meaning
PEP_GC_DAILY | Triggers a grouping every time the date changes.
PEP_GC_WEEKLY | Triggers a grouping every time the date changes from one week to the next (a week runs from Sunday through Saturday).
PEP_GC_BIWEEKLY | Triggers a grouping every time the date changes from one two-week period to the next.
PEP_GC_SEMIMONTHLY | Triggers a grouping every time the date changes from one half-month period to the next.
PEP_GC_MONTHLY | Triggers a grouping every time the date changes from one month to the next.
PEP_GC_QUARTERLY | Triggers a grouping every time the date changes from one calendar quarter to the next.
PEP_GC_SEMIANNUALLY | Triggers a grouping every time the date changes from one half-year period to the next.
PEP_GC_ANNUALLY | Triggers a grouping every time the date changes from one year to the next.
Value (Boolean Fields) | Meaning
PEP_GC_TOYES | Triggers a grouping every time the sort and group by field changes from No to Yes.
PEP_GC_TONO | Triggers a grouping every time the sort and group by field changes from Yes to No.
PEP_GC_EVERYYES | Triggers a grouping every time the group and sort by field value is Yes.
PEP_GC_EVERYNO | Triggers a grouping every time the group and sort by field value is No.
PEP_GC_NEXTISYES | Triggers a grouping every time the next value in the sort and group by field is Yes.
PEP_GC_NEXTISNO | Triggers a grouping every time the next value in the sort and group by field is No.

sort
Direction

Specifies one of Sort Order Constants.

Remarks

This method sets the condition of the grouping for the specified group section. This method can only replace the group condition for an existing group. It cannot create a new group. Use this function whenever you want to change the grouping at print time, for example, to print one report grouped in several different ways.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetGroupCondition


CRPEJob::SetGroupSelectionFormula

Use SetGroupSelectionFormula to set the formula text for the group selection formula. This method is often used with CRPEJob::GetGroupSelectionFormula to identify and then change an existing group selection formula in response to a user selection at print time.

Syntax

SetGroupSelectionFormula (formulaText CHAR(*)) RETURNING BOOLEAN

Parameter

formulaText

Specifies the new group selection formula that you want to assign to the report.

Returns
  • TRUE if the call is successful.
  • FALSE if there is an error in the formula, or if the call fails.
Related Topics

PESetGroupSelectionFormula


CRPEJob::SetLineHeight

Use SetLineHeight to set the line height for the specified section. This method can be used for setting up a report to print on preprinted forms. It can also be used if you want to insure the size of a line in relation to the font size. For example, this method might be used to specify a 12 point line with 10 point type.

Syntax
SetLineHeight (sectionCode SMALLINT, lineN SMALLINT, height SMALLINT,
ascent SMALLINT) RETURNING BOOLEAN
Parameters

sectionCode | Specifies the Section Codes, for the section of the report for which you want to set line height.
lineN | Specifies the 0-based number of the line for which you are setting the height. The first line in a section is line number 0, the next is 1, etc. Use PEP_ALLLINES to specify all lines in the section.
height | Specifies the height, in twips, of the line.
ascent | Specifies the ascent, in twips, of the line. Line ascent is the distance from the baseline of the font to the top of the line space.

Returns
  • TRUE if the call is successful.
  • FALSE if there is an invalid selection, or if the call fails.


CRPEJob::SetMargins

Use SetMargins to set the page margins for the print job. Use this method any time you want to allow the user to change margins.

Syntax

SetMargins (left SMALLINT, right SMALLINT, top SMALLINT, bottom SMALLINT) RETURNING BOOLEAN

Parameters

left | Specifies the left margin in twips.
right | Specifies the right margin in twips.
top | Specifies the top margin in twips.
bottom | Specifies the bottom margin in twips.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetMargins


CRPEJob::SetMinimumSectionHeight

Use SetMinimumSectionHeight to set the minimum height for the specified section. For example, use this method whenever you want to specify a minimum section height for printing on pre-printed forms or printing on any other kind of document with a fixed format.

Syntax

SetMinimumSectionHeight (sectionCode SMALLINT, height SMALLINT) RETURNING BOOLEAN

Parameters

sectionCode | Specifies the Section Codes, for the section of the report for which you want to set minimum section height.
height | Specifies the minimum height in twips of the specified section.

Returns
  • TRUE if the call is successful.
  • FALSE if an invalid section has been specified, or if the call fails.


CRPEJob::SetNDetailCopies

Use SetNDetailCopies to set the number of times the Details section of the report is to be printed. For example, you can use this method to print multiple copies of labels for a customer, multiple copies of a purchase order, or multiple copies of anything set up in the Details section of the report.

Syntax

SetNDetailCopies (nCopies SMALLINT) RETURNING BOOLEAN

Parameter

nCopies

Specifies the number of copies of the detail section of the report to be printed.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetNDetailCopies


CRPEJob::SetNthGroupSortField

Use SetNthGroupSortField to specify that the specified group summary field is sorted in the specified direction (ascending or descending). This method does not create a new group, but will sort an existing group summary field.

Syntax

SetNthGroupSortField (sortFieldN SMALLINT, field CHAR(*), direction SMALLINT) RETURNING BOOLEAN

Parameters

sortFieldN | Specifies the 0-based number of the group sort field that you want to set. The first group sort field added to the report is field 0, the second is 1, etc. If the report has N group sort fields, the function can be called with this parameter between 0 and N-1 to replace an existing group sort field. Call the function with this parameter equal to N to add a new group sort field.
field | Specifies the name of the group field to be sorted.
direction | Specifies one of the Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetNthAlertConditionFormula


CRPEJob::SetNthParam

Syntax

SetNthParam (paramN SMALLINT, paramValue CHAR (*)) RETURNING BOOLEAN

Parameters

paramN | Specifies which parameter in the stored procedure you want to set the value of. The first parameter of a stored procedure is 0, the second is 1, etc.
paramValue | Specifies the new value of the indicated parameter. This value must be a string. Please see Remarks below.

Remarks

Sets the value of a parameter in a stored procedure. Use this method when working with stored procedures in SQL database tables to set the value of a parameter in a stored procedure. When passing parameter values, all parameter values must be passed as string values. If you wish to pass a numeric value, pass the value in quotes like this: "100".

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetNthParameterField


CRPEJob::SetNthSortField

Use SetNthSortField to specify that the report data is sorted according to the specified field and direction.

Syntax
SetNthSortField (sortFieldN SMALLINT, field CHAR(*), direction SMALLINT)
RETURNING BOOLEAN
Parameters

sortFieldN | Specifies the 0-based number of the sort field that you want to set. The first sort field added to the report is field 0, the second is 1, etc. If the report has N sort fields, the function can be called with this parameter between 0 and N-1 to replace an existing sort field. Call the function with this parameter equal to N to add a new sort field.
field | Specifies the name of the field to be sorted.
direction | Specifies one of the Sort Order Constants.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetNthSortField


CRPEJob::SetNthTableLocation

Use SetNthTableLocation to set the table location information for the specified table in the report. This method is typically combined with CRPEJob::GetNthTableLocation, to identify the location of a table and then to change it.

Syntax
SetNthTableLocation (tableN SMALLINT, tableLocation CRPETableLocation)
RETURNING BOOLEAN
Parameters

tableN | Specifies the 0-based number of the table for which you want to set a new location.
tableLocation | Specifies a pointer to class CRPETableLocation.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetNthTableLocation


CRPEJob::SetNthTableLogOnInfo

Syntax
SetNthTableLogonInfo (tableN SMALLINT, logonInfo CRPELogOnInfo,
propagate BOOLEAN) RETURNING BOOLEAN
Parameters

tableN | Specifies the 0-based number of the table for which you want to set log on information.
logonInfo | Specifies a pointer to class CRPELogOnInfo.
propagate | TRUE or FALSE value indicating whether the log on information should be used for opening all tables being used in the report.

Remarks

This method sets SQL connection information for the specified table. The propagate flag may be used to cause the change to affect all tables with similar server and database properties.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetNthTableLogOnInfo


CRPEJob::SetNthTableSessionInfo

Syntax
SetNthTableSessionInfo (tableN SMALLINT, sessionInfo CRPESessionInfo,
propagate BOOLEAN) RETURNING BOOLEAN
Parameters

tableN | 0 indexed table number indicating which MS Access table in the report the session is being opened for.
sessionInfo | Specifies a pointer to class CRPESessionInfo.
propagate | TRUE or FALSE value indicating whether the session information should be used for opening all tables being used in the report.

Remarks

This methods sets session information for the specified Microsoft Access table. Many MS Access database tables require that a session be opened before the table can be used. Use this method to open the session.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetNthTableSessionInfo


CRPEJob::SetPrintDate

Syntax
SetPrintDate (v_year SMALLINT, v_month SMALLINT, v_day SMALLINT)
RETURNING BOOLEAN
Parameters

v_year | Specifies the year of the new print date.
v_month | Specifies the month of the new print date.
v_day | Specifies the day of the new print date.

Remarks

This method sets the print date for the report. This method does not schedule the report to print at a different time or day, but only changes the date that appears in any Print Date Field that appears on the report. Use this method, for example, to post date a report when it is printed before the day it is distributed.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetPrintDate


CRPEJob::SetPrintOptions

Syntax

SetPrintOptions (options CRPEPrintOptions) RETURNING BOOLEAN

Parameter

options

Specifies a pointer to class CRPEPrintOptions.

Remarks

This method may be used to set the print characteristics of a print job. Use this method any time you want to set the starting page number, the ending page number, the number of report copies, and/or collation instructions for a print job at runtime in response to user specifications.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetPrintOptions


CRPEJob::SetReportTitle

Syntax

SetReportTitle (title CHAR(*)) RETURNING BOOLEAN

Parameter

title

Specifies a new title for the report.

Remarks

This method sets the report title for the print job. Use this method whenever you need to change the title of a report at print time.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetReportTitle


CRPEJob::SetSectionFormat

Syntax

SetSectionFormat (sectionCode SMALLINT, options CRPESectionOptions) RETURNING BOOLEAN

Parameters

sectionCode | Specifies the Section Codes, for the section of the report for which you want to set the section format.
options | Specifies a pointer to class CRPESectionOptions.

Remarks

Sets the section format settings for selected sections in the specified report to the values in the CRPESectionOptions class. This method can be used to provide specialized formatting for printing invoices, form letters, printing to pre-printed forms, etc. It allows you to hide a section, insert a page break either before or after a section begins, reset the page number to 1 after a group value prints, prevent page breaks from spreading data from a single record over two pages, and to print group values only at the bottom of a page. For a complete discussion of each of these options, see class CRPESectionOptions.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetSectionFormat


CRPEJob::SetSelectionFormula

Syntax

SetSelectionFormula (formulaText CHAR(*)) RETURNING BOOLEAN

Parameter

formulaText

Specifies the new selection formula to be assigned to the report.

Remarks

This method sets the formula text for the record selection formula. CRPEJob::SetSelectionFormula is often used with CRPEJob::GetSelectionFormula, to identify and then change an existing selection formula at print time in response to a user selection.

Returns
  • TRUE if the call is successful.
  • FALSE if there is an error in the formula, or if the call fails.
Related Topics

PESetSelectionFormula


CRPEJob::SetSQLQuery

Syntax

SetSQLQuery (query CHAR(*)) RETURNING BOOLEAN

Parameter

query

The text of the new SQL query to be sent to the server.

Remarks

This method sets the SQL query that will be sent to the database server. This method can be used with CRPEJob::GetSQLQuery to retrieve and then change the SQL query for the report.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PESetSQLQuery


CRPEJob::Show...Page

Use these methods to show the specified page in the preview window. Use these methods to customize how a user moves through the pages of a report.

Syntax
ShowFirstPage () RETURNING BOOLEAN
ShowLastPage () RETURNING BOOLEAN
ShowNextPage () RETUNING BOOLEAN
ShowPreviousPage () RETURNING BOOLEAN
Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PEShow...Page


CRPEJob::ShowPrintControls

Use ShowPrintControls to toggle the display of the preview window control buttons. Use this to display default controls, or to hide default controls and provide customized controls.

Syntax

ShowPrintControls (showControls BOOLEAN) RETURNING BOOLEAN

Parameter

showControls

Boolean value indicating whether print controls will be showing in the preview window. TRUE indicates default print controls are to be displayed in the preview window. FALSE indicates no controls are to be displayed.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PEShow...Page


CRPEJob::StartJob

Use StartJob to start the processing of the print job and display the final output of that processing. This is the method that actually prints or exports the report.

Syntax

StartJob () RETURNING BOOLEAN

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PEStartPrintJob


CRPEJob::TestNthTableConnectivity

Use TestNthTableConnectivity to determine if a valid connection exists to the database for the specified table in the report. This method is typically used if you plan to print at a later time, but you want to test now to make sure everything is in order for logging on to the database table.

Syntax

TestNthTableConnectivity (tableN SMALLINT) RETURNING BOOLEAN

Parameter

tableN

Specifies the number of the table for which you want to test the connection settings. The first table added to a report is numbered 0, the second is 1, etc.

Returns
  • TRUE if the database session, log on, and location information is all correct.
  • FALSE if one or more of the above are incorrect, or if the call fails.
Related Topics

PETestNthTableConnectivity


CRPEJob::ZoomPreviewWindow

Syntax

ZoomPreviewWindow (level SMALLINT) RETURNING BOOLEAN

Parameter

level

The magnification level to which the preview window is to be "zoomed". Use one of the following values:

Value | Meaning
PEP_ZOOM_FULL_SIZE | Full page.
PEP_ZOOM_SIZE_FIT_ONE_SIDE | Fit one side (highest magnification).
PEP_ZOOM_SIZE_FIT_BOTH_SIDES | Fit both sides.

Remarks

This method "zooms" the preview window to the specified magnification level. Use this function when the report has been printed to a preview window and you need to set the magnification of the preview window to a specific level.

Returns
  • TRUE if the call is successful.
  • FALSE if the call fails.
Related Topics

PEZoomPreviewWindow


Other NewEra Classes

The following classes are discussed in this section.

class CRPEExportOptions

class CRPEGraphDataInfo

class CRPEGraphOptions

class CRPEGraphTextInfo

class CRPEJobInfo

class CRPELogOnInfo

class CRPEPrintOptions

class CRPESectionOptions

class CRPESessionInfo

class CRPETableLocation

class CRPETableType


class CRPEExportOptions

This class is used to get and set the export options of a print job. It is used by member functions CRPEJob::GetExportOptions, and CRPEJob::ExportTo.

Data Members

m_formatType | Specifies the export format to be used.
m_formatDLLName | Specifies the name of the format DLL that contains the export format to be used.
m_formatOptions | Provides additional export information specific to the format type being used.
m_nFormatOptionsBytes | Automatically assigned by CRPEJob::GetExportOptions. Unused by CRPEJob::SetExportOptions.
m_destinationType | Specifies the destination type of the exported report.
m_destinationDLLName | Specifies the name of the destination DLL that contains the destination type to be used.
m_destinationOptions | Provides additional information specific to the export destination type.
m_nDestinationOptionsBytes | Automatically assigned by CRPEJob::GetExportOptions. Unused by CRPEJob::SetExportOptions.

Constructor CRPEExportOptions::CRPEExportOptions

CRPEExportOptions::CRPEExportOptions constructs a CRPEExportOptions class object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Default Syntax

CRPEExportOptions ();

Constructor Syntax
CRPEExportOptions (formatDLLName CHAR(*) : NULL, formatType INTEGER: 0,
formatOptions FOREIGN : NULL, destinationDLLName CHAR(*) : NULL,
destinationType INTEGER : 0, destinationOptions FOREIGN : NULL);
Constructor Parameters

formatDLLName

Specifies the name of the format DLL that contains the export format to be used. Assigns this value to the CRPEExportOptions::m_formatDLLName member. Select a DLL from the following table:

To export a report in this format: | Use this DLL:
Crystal Reports Format | uxfcr.dll
Data Interchange Format | uxfdif.dll
Word for Windows Format | uxfwordw.dll
Word for DOS Format | uxfdoc.dll
WordPerfect Format | uxfdoc.dll
Quattro Pro 5.0 (WB1) Format | uxfqp.dll
Record Style Format (columns) | uxfrec.dll
Rich Text Format | uxfrtf.dll
Comma Separated Values (CSV) | uxfsepv.dll
Tab Separated Values | uxfsepv.dll
Character Separated Values | uxfsepv.dll
Text Format (ASCII) | uxftext.dll
Tab Separated Text Format | uxftext.dll
Lotus 1-2-3 (WKS) | uxfwks.dll
Lotus 1-2-3 (WK1) | uxfwks.dll
Lotus 1-2-3 (WK3) | uxfwks.dll
Excel 2.1 | uxfxls.dll
Excel 3.0 | uxfxls.dll
Excel 4.0 | uxfxls.dll

formatType

Specifies the export format to be used. Assigns this value to the CRPEExportOptions::m_formatType member. Select from the following values:

To export a report in this format: | Use this for formatType:
Crystal Reports Format | UXFCrystalReportType
Data Interchange Format | UXFDIFType
Word for Windows Format | UXFWordWinType
Word for DOS Format | UXFWordDosType
WordPerfect Format | UXFWordPerfectType
Quattro Pro 5.0 (WB1) Format | UXFQP5Type
Record Style Format (columns) | UXFRecordType
Rich Text Format | UXFRichTextFormatType
Comma Separated Values (CSV) | UXFCommaSeparatedType
Tab Separated Values | UXFTabSeparatedType
Character Separated Values | UXFCharSeparatedType
Text Format (ASCII) | UXFTextType
Tab Separated Text Format | UXFTabbedTextType
Lotus 1-2-3 (WKS) | UXFLotusWksType
Lotus 1-2-3 (WK1) | UXFLotusWk1Type
Lotus 1-2-3 (WK3) | UXFLotusWk3Type
Excel 2.1 | UXFXls2Type
Excel 3.0 | UXFXls3Type
Excel 4.0 | UXFXls4Type

formatOptions

Provides additional export information specific to the format type being used. Assigns this value to the CRPEExportOptions::m_formatOptions member. This parameter is required for only certain format types. If you assign NULL to this parameter, the Crystal Report Engine will automatically prompt the user for format information if needed. Otherwise, use a format options class from the following table:

To export a report in this format: | Use this class:
Data Interchange Format | UXFDIFOptions
Record Style Format (columns) | UXFRecordStyleOptions
Comma Separated Values (CSV) | UXFCommaTabSeparated-Options
Tab Separated Values | UXFCommaTabSeparated-Options
Character Separated Values | UXFCharSeparatedOptions

destinationDLLName

Specifies the name of the destination DLL that contains the destination type to be used. Assigns this value to the CRPEExportOptions::m_destinationDLLName member. The following options are available:

To export a report to this destination: | Use this DLL name:
Disk File | uxddisk.dll
E-mail (MAPI) | uxdmapi.dll
E-mail (VIM) | uxdvim.dll

destinationType

Specifies the destination type of the exported report. Assigns this value to the CRPEExportOptions::m_destinationType member. The following values are available:

To export a report to this destination: | Use this destination type:
Disk File | UXDDiskType
E-mail (MAPI) | UXDMapiType
E-mail (VIM) | UXDVIMType

destinationOptions

Provides additional information specific to the export destination type. Assigns this value to the CRPEExportOptions::m_destinationOptions member. If you assign NULL to this parameter, the Crystal Report Engine will automatically prompt the user for destination information when needed. Otherwise, use a destination options class from the following table:

To export a report to this destination: | Use this class:
Disk File | UXDDiskOptions
E-mail (MAPI) | UXDMAPIOptions
E-mail (VIM) | UXDVIMOptions

Related Report Engine Calls

PEExportOptions


class CRPEGraphDataInfo

The CRPEGraphDataInfo class contains information on what report data is used by a graph in the report to create the values in the graph. The class is used by CRPEJob::GetGraphData, to retrieve information regarding an existing graph and by CRPEJob::SetGraphData, to change the data used by an existing graph.

Data Members

m_rowGroupN | Specifies which group number in the report is used to create the values in the rows of the graph.
m_colGroupN | Specifies which group number in the report is used to create the values in the columns of the graph.
m_summarized FieldN | Specifies which summary field in the report is used to set the values of the risers in the graph. Summary fields are numbered in order of their creation.
m_graphDirection | Specifies the graphing direction for cross-tab reports. For normal group/total report, the direction, is always PE_GRAPH_COLS_ONLY.

Constructor CRPEGraphDataInfo::CRPEGraphDataInfo

Constructs a CRPEGraphDataInfo class object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Default Syntax

CRPEGraphDataInfo ();

Constructor Syntax
CRPEGraphDataInfo (rowGroupN SMALLINT : 0, colGroupN SMALLINT: 0
summarizedFieldN SMALLINT : 0, graphDirection SMALLINT :
PEP_GRAPH_COLS_ONLY);
Constructor Parameters

rowGroupN | Specifies which group number in the report is used to create the values in the rows of the graph. Assigns this value to the CRPEGraphDataInfo::m_rowGroupN member variable.
colGroupN | Specifies which group number in the report is used to create the values in the columns of the graph. Assigns this value to the CRPEGraphDataInfo::m_colGroupN member variable.
summarized FieldN | Specifies which summary field in the report is used to set the values of the risers in the graph. Summary fields are numbered in order of their creation. Assigns this value to the CRPEGraphDataInfo::m_summarizedFieldN member variable.
graphDirection | Specifies the graphing direction for cross-tab reports. For normal group/total report, the direction, is always PEP_GRAPH_COLS_ONLY = 1. Assigns this value to the CRPEGraphDataInfo::m_graphDirection member variable. Possible values are:
Constant | Value | Description
PEP_GRAPH_ROWS_ONLY | 0 | Use only row values in graph.
PEP_GRAPH_COLS_ONLY | 1 | Use only column values in graph.
PEP_GRAPH_MIXED_ROW_COL | 2 | Graph by row values, then by column values.
PEP_GRAPH_MIXED_COL_ROW | 3 | Graph by column values, then by row values.
PEP_GRAPH_UNKNOWN_DIRECTION | 20 | The direction of the graph is unknown.

Related Report Engine Calls

PEGraphAxisInfo


class CRPEGraphOptions

The CRPEGraphOptions class contains information on several options available with graphs and charts. This class is used by CRPEJob::GetGraphOptions, to determine what options have been set for a chart, and it is used by CRPEJob::SetGraphOptions, to change the options for a chart.

Data Members

m_graphMax Value | Specifies the maximum value that will appear in the graph. Any graph values above this value are not charted.
m_graphMinValue | Specifies the minimum value that will appear in the graph. Any graph values below this value are not charted.
m_showDataValue | Specifies whether or not to display the numeric value associated with each riser on the chart. If set to TRUE (1), a value appears in the graph for each riser.
m_showGridLine | Specifies whether or not to display grid lines on the graph.
m_verticalBars | Specifies whether to display the bars in a bar graph vertically or horizontally.
m_showLegend | Specifies whether or not to display the graph legend.
m_fontFaceName | Specifies the font for all text and values in the entire graph.

Constructor CRPEGraphOptions::CRPEGraphOptions

Constructs a CRPEGraphOptions class object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Constructor Default Syntax

CRPEGraphOptions()

Constructor Syntax
CRPEGraphOptions (graphMaxValue FLOAT : 0, graphMinValue FLOAT : 0,
showDataValue BOOLEAN : FALSE, showGridLine BOOLEAN : FALSE,
verticalBars BOOLEAN : FALSE, showLegend BOOLEAN : FALSE, fontFaceName
CHAR (*) : NULL)
Constructor Parameters

graphMaxValue | Specifies the maximum value that will appear in the graph. Any graph values above this value are not charted. Assigns this value to the CRPEGraphOptions::m_graphMaxValue member variable.
graphMinValue | Specifies the minimum value that will appear in the graph. Any graph values below this value are not charted. Assigns this value to the CRPEGraphOptions::m_graphMinValue member variable.
showDataValue | Specifies whether or not to display the numeric value associated with each riser on the chart. If set to TRUE, a value appears in the graph for each riser. Assigns this value to the CRPEGraphOptions::m_showDataValue member variable.
showGridLine | Specifies whether or not to display grid lines on the graph. Assigns this value to the CRPEGraphOptions::m_showGridLine member variable.
verticalBars | Specifies whether to display the bars in a bar graph vertically or horizontally. Assigns this value to the CRPEGraphOptions::m_verticalBars member variable.
showLegend | Specifies whether or not to display the graph legend. Assigns this value to the CRPEGraphOptions::m_showLegend member variable.
fontFaceName | Specifies the font for all text and values in the entire graph. Assigns this value to the CRPEGraphOptions::m_fontFaceName member variable.

Related Report Engine Calls

PEGraphOptionInfo


class CRPEGraphTextInfo

The CRPEGraphTextInfo class contains information about the text that appears with a graph. This class is used with the methods CRPEJob::GetGraphText, and CRPEJob::SetGraphText.

Data Members

m_graphTitle | Specifies the main title text that will appear above your graph.
m_graphSubTitle | Specifies the sub title text that will appear directly under the main title.
m_graphFootNote | Specifies the footnote text that will appear under your graph.
m_graphGroupsTitle | Specifies the title of the groups which are being graphed.
m_graphSeriesTitle | Specifies the title of the series which is being graphed.
m_graphXAxisTitle | Specifies the title text that will appear for the X axis. Not valid for Pie graphs.
m_graphYAxisTitle | Specifies the title text that will appear for the Y axis. Not valid for Pie graphs.
m_graphZAxisTitle | Specifies the title text that will appear for the Z axis. This value is only valid for 3D graphs.

Constructor CRPEGraphTextInfo::CRPEGraphTextInfo
Constructor Default Syntax

CRPEGraphTextInfo ();

Constructor Syntax
CRPEGraphTextInfo (graphSubTitle CHAR(*) : NULL, graphFootNote CHAR(*) :
NULL, graphGroupsTitle CHAR(*) : NULL, graphSeriesTitle CHAR(*) : NULL,
graphXAxisTitle CHAR(*) : NULL, graphYAxisTitle CHAR(*) : NULL,
graphZAxisTitle CHAR(*) : NULL);
Constructor Parameters

graphTitle | Specifies the main title text that will appear above your graph. Assigns this title to the CRPEGraphTextInfo::m_graphTitle member variable.
graphSubTitle | Specifies the sub title text that will appear directly under the main title. Assigns this title to the CRPEGraphTextInfo::m_graphSubTitle member variable.
graphFootNote | Specifies the footnote text that will appear under your graph. Assigns this text to the CRPEGraphTextInfo::m_graphFootNote member variable.
graphGroupsTitle | Specifies the title of the groups which are being graphed. Assigns this title to the CRPEGraphTextInfo::m_graphGroupsTitle member variable.
graphSeriesTitle | Specifies the title of the series which is being graphed. Assigns this title to the CRPEGraphTextInfo::m_graphSeriesTitle member variable.
graphXAxisTitle | Specifies the title text that will appear for the X axis. Not valid for Pie graphs. Assigns this title to the CRPEGraphTextInfo::m_graphXAxisTitle member variable.
graphYAxisTitle | Specifies the title text that will appear for the Y axis. Not valid for Pie graphs. Assigns this title to the CRPEGraphTextInfo::m_graphYAxisTitle member variable.
graphZAxisTitle | Specifies the title text that will appear for the Z axis. Only valid for 3D graphs. Assigns this title to the CRPEGraphTextInfo::m_graphZAxisTitle member variable.

Remarks

Constructs a CRPEGraphTextInfo class object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Related Report Engine Calls

PEGraphAxisInfo

PEGraphOptionInfo

PEGraphTypeInfo


class CRPEJobInfo

This class is used by the member function CRPEJob::GetJobStatus. Status information concerning the job is returned through this class.

Data Members

Upon construction of the structure, all members are initialized to zero except m_printEnded which is initialized to FALSE.

m_numRecordsRead | Specifies the number of records actually processed.
m_numRecords Selected | Specifies the number of records selected for inclusion in the report out of the total number of records read.
m_numRecords Printed | Specifies the number of records actually printed.
m_displayPageN | Specifies the page number of the currently displayed page in the preview window.
m_latestPageN | Specifies the number of the last page that is currently available. Once the printing is complete, this value is the number of the last page.
m_startPageN | Specifies the number of the starting page. The value will normally be 1.
m_printEnded | Specifies whether or not the printing process is completed.

Constructor CRPEJobInfo::CRPEJobInfo

Constructs a CRPEJobInfo class object. Initializes all required members of the class.

Constructor Syntax
CRPEJobInfo (numRecordsRead INTEGER : 0, numRecordsSelected INTEGER : 0,
numRecordsPrinted INTEGER : 0, displayPageN SMALLINT : 0, latest PageN
SMALLINT : 0, startPageN SMALLINT : 0, printEnded BOOLEAN : FALSE);


class CRPELogOnInfo

This class is used by member functions CRPEngine::LogOnServer, CRPEngine::LogOffServer, CRPEJob::GetNthTableLogOnInfo, CRPEJob::SetNthTableLogOnInfo. The class is used to contain SQL connection information.

Data Members

m_serverName | Specifies the logon name for the server used to create the report.
m_databaseName | Specifies the logon name for the database used to create the report.
m_userID | Specifies the user ID necessary to log on to the server.
m_password | Specifies the password necessary to log on to the server.

Constructor CRPELogOnInfo::CRPELogOnInfo
Constructor Default Syntax

CRPELogOnInfo ();

Constructor Syntax
CRPELogOnInfo (serverName CHAR (*), databaseName CHAR (*), userID CHAR
(*), password CHAR (*));
Constructor Parameters

serverName | Specifies the logon name for the server or ODBC Datasource Name used to logon to the server. Assigns this value to the CRPELogOnInfo::m_serverName member.
databaseName | Specifies the logon name for the database used to run the report. Assigns this value to the CRPELogOnInfo::m_databaseName member.
userID | Specifies the user ID necessary to log on to the server. Assigns this value to the CRPELogOnInfo::m_userID member.
password | Specifies the password necessary to log on to the server. Assigns this value to the CRPELogOnInfo::m_password member.

Remarks

Constructs a CRPELogOnInfo class object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.


class CRPEPrintOptions

This class is used to set the print characteristics of a report. It is used with CRPEJob::SetPrintOptions.

Data Members

m_startPageN | Specifies the first page that you want to print.
m_stopPageN | Specifies the last page that you want to print.
m_nReportCopies | Specifies the number of copies that you want to print.
m_collation | Indicates whether or not you want the copies of the report to be collated (if you are printing multiple copies of a multiple page report.

Constructor CRPEPrintOptions::CRPEPrintOptions
Constructor Default Syntax

CRPEPrintOptions ();

Constructor Syntax
CRPEPrintOptions (startPageN SMALLINT : 0, stopPageN SMALLINT : 0,
nReportCopies SMALLINT : 0, collation SMALLINT : PEP_DEFAULTCOLLATION);
Constructor Parameters

startPageN | Specifies the first page that you want to print. Assigns this value to the CRPEPrintOptions::m_startPageN member.
stopPageN | Specifies the last page that you want to print. Assigns this value to the CRPEPrintOptions::m_stopPageN member.
nReportCopies | Specifies the number of copies that you want to print. Assigns this value to the CRPEPrintOptions::m_nReportCopies member.
collation | Indicates whether or not you want the copies of the report to be collated (if you are printing multiple copies of a multiple page report). Assigns this value to the CRPEPrintOptions::m_collation member. Possible values are:
Value | Meaning
PEP_UNCOLLATED | Prints multiple copies of a multiple page report uncollated (Page order = 1, 1, 1, 2, 2, 2, 3, 3, 3, etc.).
PEP_COLLATED | Prints multiple copies of a multiple page report collated (Page order = 1, 2, 3..., 1, 2, 3..., etc.).
PEP_DEFAULTCOLLATION | Prints multiple copies of a multiple page report using the collation settings specified in the report.

Remarks

Constructs a CRPEPrintOptions class object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.

Related Report Engine Calls

PEPrintOptions


class CRPESectionOptions

This class contains specifications for formatting selected report sections. This information is used by the methods CRPEJob::GetSectionFormat, and CRPEJob::SetSectionFormat.

Data Members

m_visible | Specifies whether or not the selected section is to be visible. Use TRUE to keep the section visible, FALSE to hide the section.
m_newPageBefore | Specifies whether or not the Crystal Report Engine is to insert a page break before the section is printed. Use TRUE to insert a page break, FALSE to leave it without a page break.
m_newPageAfter | Specifies whether or not the Crystal Report Engine is to insert a page break after the section is printed. Use TRUE to insert a page break, FALSE to leave it without a page break.
m_keepTogether | Specifies whether or not the Crystal Report Engine is to keep all lines of the section together, either on the current page (if there is room), or on the next page. Pass TRUE to keep the lines together, FALSE to allow the Crystal Report Engine to split section data from one page to the next if necessary.
m_suppressBlank Lines | Specifies whether or not the Crystal Report Engine is to eliminate lines from your report that are blank due to fields being suppressed (zeroes, duplicates, and hidden fields). TRUE eliminates blank lines. FALSE retains them.
m_resetPageNAfter | Specifies whether or not the Crystal Report Engine is to reset the page number to one (1) for the following page, after it prints a group total. Use TRUE to reset the page number, FALSE to keep standard numbering.
m_printAtBottom OfPage | Specifies whether or not the Crystal Report Engine is to cause each group summary value to print only at the bottom of a page. Use TRUE to print summaries at the bottom of the page, FALSE to print summaries immediately after the group.

Constructor CRPESectionOptions::CRPESectionOptions
Constructor Syntax
CRPESectionOptions (visible BOOLEAN : FALSE, newPageBefore BOOLEAN :
FALSE, newPageAfter BOOLEAN : FALSE, keepTogether BOOLEAN : FALSE,
suppressBlankLines BOOLEAN : FALSE, resetPageNAfter BOOLEAN : FALSE,
printAtBottomOfPage BOOLEAN : FALSE)
Constructor Parameters

visible | Specifies whether or not the selected section is to be visible. Use TRUE to keep the section visible, FALSE to hide the section. Assigns this value to the CRPESectionOptions::m_visible member.
newPageBefore | Specifies whether or not the Crystal Report Engine is to insert a page break before the section is printed. Use TRUE to insert a page break, FALSE to leave it without a page break. Assigns this value to the CRPESectionOptions::m_newPageBefore member.
newPageAfter | Specifies whether or not the Crystal Report Engine is to insert a page break after the section is printed. Use TRUE to insert a page break, FALSE to leave it without a page break. Assigns this value to the CRPESectionOptions::m_newPageAfter member.
keepTogether | Specifies whether or not the Crystal Report Engine is to keep all lines of the section together, either on the current page (if there is room), or on the next page. Pass TRUE to keep the lines together, FALSE to allow the Crystal Report Engine to split section data from one page to the next if necessary. Assigns this value to the CRPESectionOptions::m_keepTogether member.
suppressBlank Lines | Specifies whether or not the Crystal Report Engine is to eliminate lines from your report that are blank due to fields being suppressed (zeroes, duplicates, and hidden fields). TRUE eliminates blank lines. FALSE retains them. Assigns this value to the CRPESectionOptions::m_suppressBlankLines member.
resetPageNAfter | Specifies whether or not the Crystal Report Engine is to reset the page number to one (1) for the following page, after it prints a group total. Use TRUE to reset the page number, FALSE to keep standard numbering. Assigns this value to the CRPESectionOptions::m_resetPageNAfter member.
printAtBottom OfPage | Specifies whether or not the Crystal Report Engine is to cause each group summary value to print only at the bottom of a page. Use TRUE to print summaries at the bottom of the page, FALSE to print summaries immediately after the group. Assigns this value to the CRPESectionOptions::m_printAtBottomOfPage member.

Remarks
  • Constructs a CRPESectionOptions class object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.
  • Use PEP_UNCHANGED with any parameter to let the Crystal Report Engine leave the setting as it is specified in the report file.
Related Report Engine Calls

PESectionOptions


class CRPESessionInfo

This class is used to get and set the session information (user ID and password) for password protected Microsoft Access databases. It is used with the member functions CRPEJob::GetNthTableSessionInfo, and CRPEJob::SetNthTableSessionInfo.

Data Members

m_userID | Specifies the user ID needed for logging on to the MS Access system.
m_password | Specifies the password needed for logging on to the MS Access system.
m_sessionHandle | The handle to the current MS Access session.

Constructor CRPESessionInfo::CRPESessionInfo
Constructor Default Syntax

CRPESessionInfo ();

Constructor Syntax

CRPESessionInfo (userID CHAR(*) : NULL, password CHAR(*) : NULL, sessionHandle INTEGER : 0);

Constructor Parameters

userID | Specifies the user ID needed for logging on to the MS Access system. Assigns this value to the CRPESessionInfo::m_userID member.
password | Specifies the password needed for logging on to the MS Access system. Assigns this value to the CRPESessionInfo::m_password member.
sessionHandle | The handle to the current MS Access session. Assigns this value to the CRPESessionInfo::m_sessionHandle member.

Remarks

Constructs a CRPESessionInfo class object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.


class CRPETableLocation

This class is used to get and set table location information. It is used with CRPEJob::GetNthTableLocation, and CRPEJob::SetNthTableLocation.

Data Member

m_location

Specifies the database location.

Constructor CRPETableLocation::CRPETableLocation
Constructor Syntax

CRPETableLocation (location CHAR(*) : NULL);

Constructor Parameter

location

Specifies the database location. Assigns this value to the CRPETableLocation::m_location member.

Remarks

Constructs a CRPETableLocation class object. Call the constructor with no parameters to allow the Class Library to initialize all member variables with default values. Pass parameters to the constructor to assign specific values to each member variable.


class CRPETableType

This class is used to determine information about a specific table used in the report. It is used by CRPEJob::GetNthTableSessionInfo.

Data Members

m_dllName | Specifies the name of the appropriate database DLL for the table of interest.
m_descriptiveName | Specifies the name of the table of interest.
m_dbType | Specifies the type of database that contains the table of interest.

Constructor CRPETableType::CRPETableType

Constructs a CRPETableType class object. Initializes all members of the class.

Constructor Syntax
CRPETableType (dbType SMALLINT : PEP_DT_SQL, dllName CHAR(*) : NULL,
descriptiveName: CHAR(*) : NULL);


Class Constants

The following constants, some of the more commonly used class constants, are discussed in this section.

Chart Type Constants

Error Codes

Section Codes

Sort Order Constants


Chart Type Constants

Constant | Description
PEP_SIDE_BY_SIDE_BAR_GRAPH | Side By Side bar charts.
PEP_STACKED_BAR_GRAPH | Stacked bar charts.
PEP_PERCENT_BAR_GRAPH | Percent bar charts.
PEP_FAKED_3D_SIDE_BY_SIDE_BAR_GRAPH | 3D Side By Side bar charts.
PEP_FAKED_3D_STACKED_BAR_GRAPH | 3D Stacked bar charts.
PEP_FAKED_3D_PERCENT_BAR_GRAPH | 3D Percent bar charts.
PEP_PIE_GRAPH | Pie charts.
PEP_MULTIPLE_PIE_GRAPH | Multiple Pie charts.
PEP_PROPORTIONAL_MULTI_PIE_GRAPH | Weighted Pie charts.
PEP_LINE_GRAPH | Line charts.
PEP_AREA_GRAPH | Area charts.
PEP_THREED_BAR_GRAPH | 3D bar charts.
PEP_USER_DEFINED_GRAPH | User Defined chart type.
PEP_UNKNOWN_TYPE_GRAPH | Unknown chart type.


Error Codes

Constant | Value | Description
CONSTANT PEP_ERR_NOERROR | INTEGER = 0 |
CONSTANT PEP_ERR_NOTENOUGHMEMORY | INTEGER = 500 |
CONSTANT PEP_ERR_INVALIDJOBNO | INTEGER = 501 |
CONSTANT PEP_ERR_INVALIDHANDLE | INTEGER = 502 |
CONSTANT PEP_ERR_STRINGTOOLONG | INTEGER = 503 |
CONSTANT PEP_ERR_NOSUCHREPORT | INTEGER = 504 |
CONSTANT PEP_ERR_NODESTINATION | INTEGER = 505 |
CONSTANT PEP_ERR_BADFILENUMBER | INTEGER = 506 |
CONSTANT PEP_ERR_BADFILENAME | INTEGER = 507 |
CONSTANT PEP_ERR_BADFIELDNUMBER | INTEGER = 508 |
CONSTANT PEP_ERR_BADFIELDNAME | INTEGER = 509 |
CONSTANT PEP_ERR_BADFORMULANAME | INTEGER = 510 |
CONSTANT PEP_ERR_BADSORTDIRECTION | INTEGER = 511 |
CONSTANT PEP_ERR_ENGINENOTOPEN | INTEGER = 512 |
CONSTANT PEP_ERR_INVALIDPRINTER | INTEGER = 513 |
CONSTANT PEP_ERR_PRINTFILEEXISTS | INTEGER = 514 |
CONSTANT PEP_ERR_BADFORMULATEXT | INTEGER = 515 |
CONSTANT PEP_ERR_BADGROUPSECTION | INTEGER = 516 |
CONSTANT PEP_ERR_ENGINEBUSY | INTEGER = 517 |
CONSTANT PEP_ERR_BADSECTION | INTEGER = 518 |
CONSTANT PEP_ERR_NOPRINTWINDOW | INTEGER = 519 |
CONSTANT PEP_ERR_JOBALREADYSTARTED | INTEGER = 520 |
CONSTANT PEP_ERR_BADSUMMARYFIELD | INTEGER = 521 |
CONSTANT PEP_ERR_NOTENOUGHSYSRES | INTEGER = 522 |
CONSTANT PEP_ERR_BADGROUPCONDITION | INTEGER = 523 |
CONSTANT PEP_ERR_JOBBUSY | INTEGER = 524 |
CONSTANT PEP_ERR_BADREPORTFILE | INTEGER = 525 |
CONSTANT PEP_ERR_NODEFAULTPRINTER | INTEGER = 526 |
CONSTANT PEP_ERR_SQLSERVERERROR | INTEGER = 527 |
CONSTANT PEP_ERR_BADLINENUMBER | INTEGER = 528 |
CONSTANT PEP_ERR_DISKFULL | INTEGER = 529 |
CONSTANT PEP_ERR_FILEERROR | INTEGER = 530 |
CONSTANT PEP_ERR_INCORRECTPASSWORD | INTEGER = 531 |
CONSTANT PEP_ERR_BADDATABASEDLL | INTEGER = 532 |
CONSTANT PEP_ERR_BADDATABASEFILE | INTEGER = 533 |
CONSTANT PEP_ERR_ERRORINDATABASEDLL | INTEGER = 534 |
CONSTANT PEP_ERR_DATABASESESSION | INTEGER = 535 |
CONSTANT PEP_ERR_DATABASELOGON | INTEGER = 536 |
CONSTANT PEP_ERR_DATABASELOCATION | INTEGER = 537 |
CONSTANT PEP_ERR_BADSTRUCTSIZE | INTEGER = 538 |
CONSTANT PEP_ERR_BADDATE | INTEGER = 539 |
CONSTANT PEP_ERR_BADEXPORTDLL | INTEGER = 540 |
CONSTANT PEP_ERR_ERRORINEXPORTDLL | INTEGER = 541 |
CONSTANT PEP_ERR_PREVATFIRSTPAGE | INTEGER = 542 |
CONSTANT PEP_ERR_NEXTATLASTPAGE | INTEGER = 543 |
CONSTANT PEP_ERR_CANNOTACCESSREPORT | INTEGER = 544 |
CONSTANT PEP_ERR_USERCANCELLED | INTEGER = 545 |
CONSTANT PEP_ERR_OLE2NOTLOADED | INTEGER = 546 |
CONSTANT PEP_ERR_BADCROSSTABGROUP | INTEGER = 547 |
CONSTANT PEP_ERR_NOCTSUMMARIZEDFIELD | INTEGER = 548 |
CONSTANT PEP_ERR_DESTINATIONNOTEXPORT | INTEGER = 549 |
CONSTANT PEP_ERR_INVALIDPAGENUMBER | INTEGER = 550 |
CONSTANT PEP_ERR_NOTSTOREDPROCEDURE | INTEGER = 552 |
CONSTANT PEP_ERR_INVALIDPARAMETER | INTEGER = 553 |
CONSTANT PEP_ERR_GRAPHNOTFOUND | INTEGER = 554 |
CONSTANT PEP_ERR_INVALIDGRAPHTYPE | INTEGER = 555 |
CONSTANT PEP_ERR_INVALIDGRAPHDATA | INTEGER = 556 |
CONSTANT PEP_ERR_CANNOTMOVEGRAPH | INTEGER = 557 |
CONSTANT PEP_ERR_INVALIDGRAPHTEXT | INTEGER = 558 |
CONSTANT PEP_ERR_INVALIDGRAPHOPT | INTEGER = 559 |
CONSTANT PEP_ERR_BADSECTIONHEIGHT | INTEGER = 560 |
CONSTANT PEP_ERR_BADVALUETYPE | INTEGER = 561 |
CONSTANT PEP_ERR_INVALIDSUBREPORTNAME | INTEGER = 562 |
CONSTANT PEP_ERR_NOPARENTWINDOW | INTEGER = 564 | No dialog parent window.
CONSTANT PEP_ERR_INVALIDZOOMFACTOR | INTEGER = 565 | Invalid zoom factor.
CONSTANT PEP_ERR_PAGESIZEOVERFLOW | INTEGER = 567 |
CONSTANT PEP_ERR_LOWSYSTEMRESOURCES | INTEGER = 568 |
CONSTANT PEP_ERR_INVALIDNEGATIVEVALUE | INTEGER = 572 |
CONSTANT PEP_ERR_INVALIDMEMORYPOINTER | INTEGER = 573 |
CONSTANT PEP_ERR_INVALIDPARAMETERNUMBER | INTEGER = 594 |
CONSTANT PEP_ERR_SQLSERVERNOTOPENED | INTEGER = 599 |
CONSTANT PEP_ERR_NOTIMPLEMENTED | INTEGER = 999 |


Section Codes

Constant | Description
PEP_ALLSECTIONS | All sections.
PEP_HEADERSECTION | Page Header section.
PEP_GROUPHEADER | Group Header section.
PEP_DETAILSECTION | Details section.
PEP_GROUPFOOTER | Group Footer section.
PEP_GRANDTOTALSECTION | Grand Total section.
PEP_FOOTERSECTION | Page Footer section.


Sort Order Constants

Constant | Description
PEP_SF_ASCENDING | Sorts data in ascending order (A to Z, 1 to 9).
PEP_SF_DESCENDING | Sorts data in descending order (Z to A, 9 to 1).


Visual Basic Wrapper for the Crystal Report Engine

This section provides information on the functions and structures included in the Visual Basic wrapper for the Crystal Report Engine (Crwrap.bas). Special structures and functions have been created for Visual Basics native 4-byte alligned type.

Click the appropriate link to jump to that section:

  • Visual Basic Wrapper for the Crystal Report Engine Structures
  • Visual Basic Wrapper for the Crystal Report Engine Functions


Visual Basic Wrapper for the Crystal Report Engine Structures

Click the structure of interest from the following list for further information:

  • crDEVMODE
4-byte aligned structures
  • PEGraphOptions4
  • PEJobInfo4
  • PELogOnInfo4
  • PESessionInfo4
  • PETableType4


crDEVMODE

The crDEVMODE Structure is a Windows API structure that contains information about a printer driver's initialization and environment data. An application passes this structure to the DeviceCapabilities and ExtDeviceMode functions. It is used by the crPESelectPrinter and crPEGetSelectedPrinter functions.

Type crDEVMODE

    dmDriverVersion As Integer

    ' printer driver version number (usually not required)

    dmFields As Long

    'flags indicating fields to modify (required)

    dmOrientation As Integer

    dmPaperSize As Integer

    dmPaperLength As Integer

    dmPaperWidth As Integer

    dmScale As Integer

    dmCopies As Integer

    dmDefaultSource As Integer

    dmPrintQuality As Integer

    dmColor As Integer

    dmDuplex As Integer

    dmYResolution As Integer

    dmTTOption As Integer

End Type
Members

dmDriverVersion | Specifies the printer driver version number assigned by the printer driver developer.
dmFields | Specifies a set of flags that indicate which of the remaining members in the crDEVMODE structure have been initialized. It can be any combination (or it can be none) of the following values:
Constant | Value
DM_ORIENTATION | &H1
DM_PAPERSIZE | &H2
DM_PAPERLENGTH | &H4
DM_PAPERWIDTH | &H8
DM_SCALE | &H10
DM_COPIES | &H100
DM_DEFAULTSOURCE | &H200
DM_PRINTQUALITY | &H400
DM_COLOR | &H800
DM_DUPLEX | &H1000
DM_YRESOLUTION | &H2000
DM_TTOPTION | &H4000

Note: A printer driver supports only those members that are appropriate for the printer technology.

dmOrientation

Specifies the orientation of the paper. It can be either DMORIENT_PORTRAIT (1) or DMORIENT_LANDSCAPE (2).

dmPaperSize

Specifies the size of the paper to print on. This member may be set to zero if the length and width of the paper are specified by the dmPaperLength and dmPaperWidth members, respectively.

Note: The PostScript driver mistakenly uses DM_PAPER_ values between 50 and 56. Don't use this range when defining paper sizes.

Otherwise, the dmPaperSize member can be set to one of the following predefined values:

Constant | Description
DMPAPER_FIRST | DMPAPER_LETTER
DMPAPER_LETTER | Letter, 8 1/2 x 11 in.
DMPAPER_LETTERSMALL | Letter Small, 8 1/2 x 11 in.
DMPAPER_TABLOID | Tabloid, 11 x 17 in.
DMPAPER_LEDGER | Ledger, 17 x 11 in.
DMPAPER_LEGAL | Legal, 8 1/2 x 14 in.
DMPAPER_STATEMENT | Statement, 5 1/2 x 8 1/2 in.
DMPAPER_EXECUTIVE | Executive, 7 1/2 x 10 1/2 in.
DMPAPER_A3 | A3, 297 x 420 mm
DMPAPER_A4 | A4, 210 x 297 mm
DMPAPER_A4SMALL | A4 Small, 210 x 297 mm
DMPAPER_A5 | A5, 148 x 210 mm
DMPAPER_B4 | B4, 250 x 354 mm
DMPAPER_B5 | B5, 182 x 257 mm
DMPAPER_FOLIO | Folio, 8 1/2 x 13 in.
DMPAPER_QUARTO | Quarto, 215 x 275 mm
DMPAPER_10X14 | 10 x 14 in.
DMPAPER_11X17 | 11 x 17 in.
DMPAPER_NOTE | Note, 8 1/2 x 11 in.
DMPAPER_ENV_9 | Envelope #9, 3 7/8 x 8 7/8 in.
DMPAPER_ENV_10 | Envelope #10, 4 1/8 x 9 1/2 in.
DMPAPER_ENV_11 | Envelope #11, 4 1/2 x 10 3/8 in.
DMPAPER_ENV_12 | Envelope #12, 4 1/2 x 11 in.
DMPAPER_ENV_14 | Envelope #14, 5 x 11 1/2 in.
DMPAPER_CSHEET | C size sheet
DMPAPER_DSHEET | D size sheet
DMPAPER_ESHEET | E size sheet
DMPAPER_ENV_DL | Envelope DL, 110 x 220 mm
DMPAPER_ENV_C3 | Envelope C3, 324 x 458 mm
DMPAPER_ENV_C4 | Envelope C4, 229 x 324 mm
DMPAPER_ENV_C5 | Envelope C5, 162 x 229 mm
DMPAPER_ENV_C6 | Envelope C6, 114 x 162 mm
DMPAPER_ENV_C65 | Envelope C65, 114 x 229 mm
DMPAPER_ENV_B4 | Envelope B4, 250 x 353 mm
DMPAPER_ENV_B5 | Envelope B5, 176 x 250 mm
DMPAPER_ENV_B6 | Envelope B6, 176 x 125 mm
DMPAPER_ENV_ITALY | Envelope, 110 x 230 mm
DMPAPER_ENV_MONARCH | Envelope Monarch, 3 7/8 x 7 1/2 in.
DMPAPER_ENV_PERSONAL | Envelope, 3 5/8 x 6 1/2 in.
DMPAPER_FANFOLD_US | U.S. Standard Fanfold, 14 7/8 x 11 in.
DMPAPER_FANFOLD_STD_GERMAN | German Standard Fanfold, 8 1/2 x 12 in.
DMPAPER_FANFOLD_LGL_GERMAN | German Legal Fanfold, 8 1/2 x 13 in.
DMPAPER_LAST | German Legal Fanfold, 8 1/2 x 13 in.
DMPAPER_USER | User-defined
dmPaperLength | Specifies a paper length in tenths of a millimeter. This parameter overrides the paper length specified by the dmPaperSize member, either for custom paper sizes or for such devices as dot-matrix printers that can print on a variety of page sizes.
dmPaperWidth | Specifies a paper width in tenths of a millimeter. This parameter overrides the paper width specified by the dmPaperSize member.
dmScale | Specifies the factor by which the printed output is to be scaled. The apparent page size is scaled from the physical page size by a factor of dmScale/100. For example, a letter-size paper with a dmScale value of 50 would contain as much data as a page of size 17 by 22 inches because the output text and graphics would be half their original height and width.
dmCopies | Specifies the number of copies printed if the device supports multiple-page copies.
dmDefaultSource | Specifies the default bin from which the paper is fed. The application can override this value by using the GETSETPAPERBINS escape. This member can be one of the following values:
Constant | Value
DMBIN_FIRST | 1
DMBIN_UPPER | 1
DBMIN_ONLYONE | 1
DMBIN_LOWER | 2
DMBIN_MIDDLE | 3
DMBIN_MANUAL | 4
DMBIN_ENVELOPE | 5
DMBIN_ENVMANUAL | 6
DBMIN_AUTO | 7
DMBIN_TRACTOR | 8
DMBIN_SMALLFMT | 9
DMBIN_LARGEFMT | 10
DMBIN_LARGECAPACITY | 11
DMBIN_CASSETTE | 14
DMBIN_LAST | DBIM_CASSETTE

Note: A range of values is reserved for device-specific bins. To be consistent with initialization information, the GETSETPAPERBINS and ENUMPAPERBINS escapes use these values.

dmPrintQuality

Specifies the printer resolution. Following are the four predefined device-independent values:

Constant | Value
DMRES_DRAFT | -1
DMRES_LOW | -2
DMRES_MEDIUM | -3
DMRES_HIGH | -4

Note: If a positive value is given, it specifies the number of dots per inch (DPI) and is therefore device-dependent.

Note: If the printer initializes the dmYResolution member, the dmPrintQuality member specifies the x-resolution of the printer, in dots per inch.

dmColor

Specifies whether color printer renders color or monochrome output. Possible values are:

Constant | Value
DMCOLOR_MONOCHROME | 1
DMCOLOR_COLOR | 2

dmDuplex

Specifies duplex (double-sided) printing for printers capable of duplex printing. This member can be one of the following values:

Constant | Value
DMDUP_SIMPLEX | 1
DMDUP_ VERTICAL | 2
DMDUP_ HORIZONTAL | 3
dmYResolution | Specifies the y-resolution of the printer in dots per inch. If the printer initializes this member, the dmPrintQuality member specifies the x-resolution of the printer in dots per inch.
dmTTOption | Specifies how TrueType fonts should be printed. It can be one of the following values:
Constant | Value
DMTT_BITMAP | Print TrueType fonts as graphics. This is the default action for dot-matrix printers.
DMTT_DOWNLOAD | Download TrueType fonts as soft fonts. This is the default action for Hewlett-Packard printers that use Printer Control Language (PCL).
DMTT_SUBDEV | Substitute device fonts for TrueType fonts. This is the default action for PostScript printers.

Remarks
  • Only drivers that are fully updated for Windows versions 3.0 and later and that export the ExtDeviceMode function use the crDEVMODE structure.
  • An application can retrieve the paper sizes and names supported by a printer by calling the DeviceCapabilities function with the DC_PAPERS, DC_PAPERSIZE, and DC_PAPERNAMES values.
  • Before setting the value of the dmTTOption member, applications should find out how a printer driver can use TrueType fonts by calling the DeviceCapabilities function with the DC_TRUETYPE value.
  • Drivers can add device-specific data immediately following the crDEVMODE structure.


PEGraphOptions4

The PEGraphOptions4 structure was specially designed for 4-byte aligned functions. It contains information on several options available with graphs and charts. This structure is used by PEGetGraphOptions4 to retrieve the current options, and by PESetGraphOptions4 to pass new options.

Type PEGraphOptions4

    StructSize As Integer

    GraphMaxValue As Double

    GraphMinValue As Double

    ShowDataValue As Long

    ShowGridLine As Long

    VerticalBars As Long

    ShowLegend As Long

    FontFaceName As String * PE_GRAPH_TEXT_LEN

End Type
Members

StructSize | Specifies the size of the PEGraphOptions4 structure. You must initialize this member to be the size of the structure, for example: options.StructSize = PE_SIZEOF_GRAPH_OPTIONS4.
GraphMaxValue | Specifies the maximum value that will appear in the graph. Any graph values above this value are not charted.
GraphMinValue | Specifies the minimum value that will appear in the graph. Any graph values below this value are not charted.
ShowDataValue | Specifies whether or not to display the numerical value associated with each riser on the chart. If set to TRUE (1), a value appears in the graph for each riser.
ShowGridLine | Specifies whether or not to display grid lines on the graph.
VerticalBars | Specifies whether to display the bars in a bar graph vertically or horizontally.
ShowLegend | Specifies whether or not to display the graph legend.
FontFaceName | Specifies the font for all text and values in the entire graph.


PEJobInfo4

The PEJobInfo4 structure was specially designed for 4-byte aligned functions. It retrieves print job process and display information data that is used by the PEGetJobStatus4 function.

Type PEJobInfo4

    StructSize As Integer

    NumRecordsRead As Long

    NumRecordsSelected As Long

    NumRecordsPrinted As Long

    DisplayPageN As Integer

    LatestPageN As Integer

    StartPageN As Integer

    PrintEnded As Long

End Type
Members

StructSize | Specifies the size of the PEJobInfo4 structure. You must initialize this member to be the size of whatever it is, for example, job.StructSize = PE_SIZEOF_JOB_INFO4.
NumRecordsRead | Specifies the number of records actually processed.
NumRecordsSelected | Specifies the number of records selected for inclusion in the report out of the total number of records read.
NumRecordsPrinted | Specifies the number of pages actually printed.
DisplayPageN | Specifies the page number of the currently displayed page.
LastPageN | Specifies the number of the last page that is currently available. Once the printing is complete, this value is the number of the last page.
StartPageN | Specifies the number of the starting page. The value will normally be 1, but you can specify something else using PESetPrintOptions.
PrintEnded | Specifies whether or not the printing process is completed. TRUE indicates that this process is completed; FALSE indicates that is not yet complete.


PELogOnInfo4

The PELogOnInfo4 structure was specially designed for 4-byte aligned functions. It contains log on information that is used by the PELogOnServer4 and PELogOffServer4 functions. The structure is used for logging on and off SQL and password-protected non-SQL databases.

Type PELogOnInfo4

    StructSize As Integer

        ServerName As String * PE_SERVERNAME_LEN

        DatabaseName  As String * PE_DATABASENAME_LEN

        UserID As String * PE_USERID_LEN

        Password  As String * PE_PASSWORD_LEN

    End Type
Members

StructSize | Specifies the size of the PELogOnInfo4 structure. You must initialize this member to the size of whatever it is, for example, info.StructSize = PE_SIZEOF_LOGON_INFO4.
ServerName | Specifies the logon name for the server used to create the report. For ODBC, use the data source name. *
DatabaseName | Specifies the logon name for the database used to create the report. *
UserID | Specifies the user ID# necessary to log on to the server. *
Password | Specifies the password necessary to log on the server. When you are using this structure to retrieve information using the crPEGetNthTableLogOnInfo function, the Password parameter is undefined.
*When you pass an empty string ("") for this parameter, the program uses the value that is already set in the report. If you want to override a value that is already set in the report, use a non-empty string (i.e., "Server A"). All strings must be null-terminated. For Netware SQL, pass the dictionary path name in ServerName and data path name in DatabaseName.


PESessionInfo4

The PESessionInfo4 structure was specially designed for 4-byte aligned functions. It contains information about the current Microsoft Access session. Use this structure with PEGetNthTableSessionInfo4 to retrieve current information and PESetNthTableSessionInfo4 to pass new information.

Type PESessionInfo4

    StructSize As Integer

    UserID As String * PE_SESS_USERID_LEN

    Password As String * PE_SESS_PASSWORD_LEN

    SessionHandle As Long

End Type
Members

StructSize | Specifies the size of the PESessionInfo4 structure. You must initialize this member to be the size of whatever it is, for example location.StructSize = PE_SIZEOF_SESSION_INFO4.
UserID | Specifies the user ID value needed for logging onto the system.
Password | Specifies the password needed for logging onto the system. When using this structure with PEGetNthTableSessionInfo4, the Password member is not defined. You specify the password when using the structure with PESetNthTableSessionInfo4.
SessionHandle | The handle to the current Microsoft Access session. The SessionHandle member is likewise undefined with the PEGetNthTableSessionInfo4 function. When you are using the PESetNthTableSessionInfo4 structure, if the SessionHandle value is 0, the Crystal Report Engine uses the UserID and Password settings. In all other cases it uses the SessionHandle value.


PETableType4

The PETableType4 structure was specially designed for 4-byte aligned functions. It contains information for identifying the type of a specified table. This information is gathered using the PEGetNthTableType4 function.

Type PETableType4

    StructSize As Integer

    DLLName As String * PE_DLL_NAME_LEN

    DescriptiveName As String * PE_FULL_NAME_LEN

    DBType As Integer

End Type
Members

StructSize | Specifies the size of the PETableType4 structure. You must initialize this member to be the size of whatever it is, for example, TableType.StructSize = PE_SIZEOF_TABLE_TYPE4.
DLLName | Specifies the name of the appropriate database DLL for the table of interest (in quotes). Select the DLL you want to use from the table below:
Use this DLL | For this standard non-SQL database
pdbbde.dll | Borland Database Engine
pdbbnd.dll | Bound reports
pdbdao.dll | DAO data sources (Access)
pdbjet.dll | Access
pdbpdx.dll | Paradox
pdbxbse.dll | dBASE, FoxPro, Clipper
pdctbtrv.dll | Btrieve
Use this DLL | For this SQL database
pdsdb22.dll | DB2/2
pdsgupta.dll | Gupta
pdsnetw.dll | Netware
pdsodbc.dll | ODBC
pdsoracl.dll | Oracle
pdssyb10.dll | Sybase 10/11
pdssybas.dll | Sybase
DescriptiveName | Specifies the name of the table of interest (in quotes).
DBType | Specifies the type of database that contains the table of interest. Select DBType from the table below:
Value | Meaning
PE_DT_STANDARD | The type for standard, non-SQL databases.
PE_DT_SQL | The type for SQL databases.


Visual Basic Wrapper for the Crystal Report Engine Functions

Click the function of interest from the following list for further information:

  • crPEDateToYearMonthDay
  • crPEExportToDisk
  • crPEExportToExch
  • crPEExportToHTML
  • crPEExportToMapi
  • crPEExportToODBC
  • crPEGetGraphOptions
  • crPEGetNthParameterType
  • crPEGetNthParameterField
  • crPEGetNthTableLocation
  • crPEGetNthTableLogOnInfo
  • crPEGetNthTableSessionInfo
  • crPEGetSelectedPrinter
  • crPELogOffServer
  • crPELogOnServer
  • crPESelectPrinter
  • crPESetGraphOptions
  • crPESetNthParameterField
  • crPESetNthTableLocation
  • crPESetNthTableLogOnInfo
  • crPESetNthTableSessionInfo
  • crPEYearMonthDayToDate
  • crvbHandleToBStr
4-byte aligned functions
  • PEGetGraphOptions4
  • PEGetJobStatus4
  • PEGetNthTableSessionInfo4
  • PEGetNthTableType4
  • PELogOffServer4
  • PELogOnServer4
  • PESetGraphOptions4
  • PESetNthTableSessionInfo4


crPEDateToYearMonthDay

The crPEDateToYearMonthDay function takes a date value and returns the year, month, and day as separate values.

Declare Function crPEDateToYearMonthDay Lib "crwrap32.dll" (ByVal nDate
As Long, ByRef nYear As Integer, ByRef nMonth As Integer, ByRef nDay As
Integer) As Integer
Parameters

nDate | Specifies the date value.
nYear | The variable to receive the year value.
nMonth | The variable to receive the month value.
nDay | The variable to receive the day value.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.


crPEExportToDisk

The crPEExportToDisk function exports a print job to a disk file.

Declare Function crPEExportToDisk Lib "crwrap32.dll" (ByVal printJob As
Integer, ByVal fileName As String, ByVal FormatDLLName As String, ByVal
formatType As Long, ByVal useNumFormat As Long, ByVal useDateFormat As
Long, ByVal StringDelimiter As String, ByVal FieldDelimiter As String)
As Integer
Parameters

printJob | Specifies the handle of the print job that you want to export.
fileName | Specifies the name of the exported file.
FormatDLLName | Specifies the pointer to the null-terminated string that contains the format DLL name. The DLL you use is determined by the format in which you want to export your report.
To export in this format | Use this DLL
Crystal Reports Format | u2fcr.dll
Data Interchange Format | u2fdif.dll
Word for Windows Forma | u2fwordw.dll
Report Definition Format | u2frdef.dll
Record Style Format (column of values) | u2frec.dll
Rich Text Format | u2frtf.dll
Comma Separated Values Format (CSV) | u2fsepv.dll
Tab Separated Values Format | u2fsepv.dll
Character Separated Values Format | u2fsepv.dll
Text Format (ASCII) | u2ftext.dll
Paginated Text Format (ASCII) | u2ftext.dll
Tab Separated Text Format | u2ftext.dll
Lotus 1-2-3 (WKS) | u2fwks.dll
Lotus 1-2-3 (WK1) | u2fwks.dll
Lotus 1-2-3 (WK3) | u2fwks.dll
Excel 2.1 | u2fxls.dll
Excel 3.0 | u2fxls.dll
Excel 4.0 | u2fxls.dll
Excel 5.0 | u2fxls.dll
HTML3 Format | u2fhtml.dll
Internet Explorer 2.0 | u2fhtml.dll
Netscape 2.0 | u2fhtml.dll
To export a report in this format | Use this formatType
Crystal Reports Format | crUXFCrystalReportType
Data Interchange Format | crUXFDIFType
Word for Windows Format | crUXFWordWinType
Report Definition Format | crUXFReportDefinitionType
Record Style Format (column of values) | crUXFRecordType
Rich Text Format | crUXFRichTextFormatType
Comma Separated Values Format (CSV) | crUXFCommaSeparatedType
Tab Separated Values Format | crUXFTabSeparatedType
Character Separated Values Format | crUXFCharSeparatedType
Text Format (ASCII) | crUXFTextType
Paginated Text Format (ASCII) | crUXFPaginatedTextType
Tab Separated Text Format | crUXFTabbedTextType
Lotus 1-2-3 (WKS) | crUXFLotusWksType
Lotus 1-2-3 (WK1) | crUXFLotusWk1Type
Lotus 1-2-3 (WK3) | crUXFLotusWk3Type
Excel 2.1 | crUXFXls2Type
Excel 3.0 | crUXFXls3Type
Excel 4.0 | crUXFXls4Type
Excel 5.0 | crUXFXls5Type
HTML3 | crUXFHTML3Type
Internet Explorer 2.0 | crUXFExplorer2Type
Netscape 2.0 | crUXFNetscape2Type

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.

Remarks
  • When calling crPEExportToDisk with the Paginated Text option, you can specify the number of lines per page using the useNumFormat argument.


crPEExportToExch

The crPEExportToExch function exports a print job to an Exchange folder.

Declare Function crPEExportToExch Lib "crwrap32.dll" (ByVal printJob As
Integer, ByVal profile As String, ByVal Password As String, ByVal
folderPath As String, ByVal FormatDLLName As String, ByVal formatType As
Long, ByVal useNumFormat As Long, ByVal useDateFormat As Long, ByVal
StringDelimiter As String, ByVal FieldDelimiter As String) As Integer
Parameters

printJob | Specifies the handle of the print job that you want to export.
profile | Specifies the Exchange profile.
Password | Specifies the Exchange password.
folderPath | Specifies the Exchange path where you want the program to place the exported file.
FormatDLLName | Specifies the pointer to the null-terminated string that contains the format DLL name. The DLL you use is determined by the format in which you want to export your report.
To export in this format | Use this DLL
Crystal Reports Format | u2fcr.dll
Data Interchange Format | u2fdif.dll
Word for Windows Format | u2fwordw.dll
Report Definition Format | u2frdef.dll
Record Style Format (column of values) | u2frec.dll
Rich Text Format | u2frtf.dll
Comma Separated Values Format (CSV) | u2fsepv.dll
Tab Separated Values Format | u2fsepv.dll
Character Separated Values Format | u2fsepv.dll
Text Format (ASCII) | u2ftext.dll
Paginated Text Format (ASCII) | u2ftext.dll
Tab Separated Text Format | u2ftext.dll
Lotus 1-2-3 (WKS) | u2fwks.dll
Lotus 1-2-3 (WK1) | u2fwks.dll
Lotus 1-2-3 (WK3) | u2fwks.dll
Excel 2.1 | u2fxls.dll
Excel 3.0 | u2fxls.dll
Excel 4.0 | u2fxls.dll
Excel 5.0 | u2fxls.dll
HTML3 Format | u2fhtml.dll
Internet Explorer 2.0 | u2fhtml.dll
Netscape 2.0 | u2fhtml.dll

formatType

Specifies the type of format you want to use from those types supported by the selected DLL. Whether the FormatDLLName you select supports only one format type (for example, uxfcr.dll) or multiple format types (for example, uxfdoc.dll), you must still fill in this parameter. Select the format type you want to use from the table below:

To export a report in this format | Use this formatType
Crystal Reports Format | crUXFCrystalReportType
Data Interchange Format | crUXFDIFType
Word for Windows Format | crUXFWordWinType
Report Definition Format | crUXFReportDefinitionType
Record Style Format (column of values) | crUXFRecordType
Rich Text Format | crUXFRichTextFormatType
Comma Separated Values Format (CSV) | crUXFCommaSeparatedType
Tab Separated Values Format | crUXFTabSeparatedType
Character Separated Values Format | crUXFCharSeparatedType
Text Format (ASCII) | crUXFTextType
Paginated Text Format (ASCII) | crUXFPaginatedTextType
Tab Separated Text Format | crUXFTabbedTextType
Lotus 1-2-3 (WKS) | crUXFLotusWksType
Lotus 1-2-3 (WK1) | crUXFLotusWk1Type
Lotus 1-2-3 (WK3) | crUXFLotusWk3Type
Excel 2.1 | crUXFXls2Type
Excel 3.0 | crUXFXls3Type
Excel 4.0 | crUXFXls4Type
Excel 5.0 | crUXFXls5Type
HTML3 | crUXFHTML3Type
Internet Explorer 2.0 | crUXFExplorer2Type
Netscape 2.0 | crUXFNetscape2Type

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.


crPEExportToHTML

The crPEExportToHTML function exports a print job to HTML format.

Declare Function crPEExportToHTML Lib "crwrap32.dll" (ByVal printJob As
Integer, ByVal htmlType As Integer, ByVal fileName As String) As Integer
Parameters

printJob | Specifies the handle of the print job that you want to export.
htmlType | Specifies the type of HTML format you want to export to. Select the format type you want to use from the table below:
To export a report in this HTML format | Use this htmlType
HTML3 | crUXFHTML3Type
Internet Explorer 2.0 | crUXFExplorer2Type
Netscape 2.0 | crUXFNetscapeType

fileName

Specifies the name of the exported file.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.

Remarks
  • When calling crPEExportToDisk with the Paginated Text option, you can specify the number of lines per page using the useNumFormat argument.


crPEExportToMapi

The crPEExportToDisk function exports a print job to MAPI.

Declare Function crPEExportToMapi Lib "crwrap32.dll" (ByVal printJob As Integer, ByVal toList As String, ByVal ccList As String, ByVal subject As String, ByVal message As String, ByVal FormatDLLName As String, ByVal formatType As Long, ByVal useNumFormat As Long, ByVal useDateFormat As Long, ByVal StringDelimiter As String, ByVal FieldDelimiter As String) As Integer

Parameters

printJob | Specifies the handle of the print job that you want to export.
subject | Specifies the pointer to the null-terminated string you want to appear as the subject line in the e-mail message.
message | Specifies the pointer to the null-terminated string you want to appear as the body of your e-mail message.
FormatDLLName | Specifies the pointer to the null-terminated string that contains the format DLL name. The DLL you use is determined by the format in which you want to export your report.
To export in this format | Use this DLL
Crystal Reports Format | u2fcr.dll
Data Interchange Format | u2fdif.dll
Word for Windows Format | u2fwordw.dll
Report Definition Format | u2frdef.dll
Record Style Format (column of values) | u2frec.dll
Rich Text Format | u2frtf.dll
Comma Separated Values Format (CSV) | u2fsepv.dll
Tab Separated Values Format | u2fsepv.dll
Character Separated Values Format | u2fsepv.dll
Text Format (ASCII) | u2ftext.dll
Paginated Text Format (ASCII) | u2ftext.dll
Tab Separated Text Format | u2ftext.dll
Lotus 1-2-3 (WKS) | u2fwks.dll
Lotus 1-2-3 (WK1) | u2fwks.dll
Lotus 1-2-3 (WK3) | u2fwks.dll
Excel 2.1 | u2fxls.dll
Excel 3.0 | u2fxls.dll
Excel 4.0 | u2fxls.dll
Excel 5.0 | u2fxls.dll
HTML3 Format | u2fhtml.dll
Internet Explorer 2.0 | u2fhtml.dll
Netscape 2.0 | u2fhtml.dll
To export a report in this format | Use this formatType
Crystal Reports Format | crUXFCrystalReportType
Data Interchange Format | crUXFDIFType
Word for Windows Format | crUXFWordWinType
Report Definition Format | crUXFReportDefinitionType
Record Style Format (column of values) | crUXFRecordType
Rich Text Format | crUXFRichTextFormatType
Comma Separated Values Format (CSV) | crUXFCommaSeparatedType
Tab Separated Values Format | crUXFTabSeparatedType
Character Separated Values Format | crUXFCharSeparatedType
Text Format (ASCII) | crUXFTextType
Paginated Text Format (ASCII) | crUXFPaginatedTextType
Tab Separated Text Format | crUXFTabbedTextType
Lotus 1-2-3 (WKS) | crUXFLotusWksType
Lotus 1-2-3 (WK1) | crUXFLotusWk1Type
Lotus 1-2-3 (WK3) | crUXFLotusWk3Type
Excel 2.1 | crUXFXls2Type
Excel 3.0 | crUXFXls3Type
Excel 4.0 | crUXFXls4Type
Excel 5.0 | crUXFXls5Type
HTML3 | crUXFHTML3Type
Internet Explorer 2.0 | crUXFExplorer2Type
Netscape 2.0 | crUXFNetscape2Type
useNumFormat | Specifies whether or not the program should save numbers in the same format (decimal places, negatives, etc.) that you have used in the report. Pass TRUE if you want the program to use the same format used in the report, FALSE if you want numbers saved in a format that has been optimized for the file format you have selected.
useDateFormat | Specifies whether or not the program should save dates in the same format (MDY, DMY, etc.) that you used in the report. Pass TRUE if you want the program to use the same format as used in the report, FALSE if you want dates saved in a format that has been optimized for the file format you have selected.
StringDelimiter | Specifies the character you want to use to enclose alphanumeric field data in the character separated values format. You can use whatever character you wish, and it must be enclosed in quotes.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.

Remarks
  • When calling crPEExportToDisk with the Paginated Text option, you can specify the number of lines per page using the useNumFormat argument.


crPEExportToODBC

The crPEExportToODBC function exports a print job to ODBC format.

Declare Function crPEExportToODBC Lib "crwrap32.dll" (ByVal printJob As Integer, ByVal dataSourceName As String, ByVal dataSourceUserID As String, ByVal dataSourcePassword As String, ByVal exportTableName As String) As Integer

Parameters

printJob | Specifies the handle of the print job that you want to export.
dataSourceName | Specifies the name of the data source that you want to export to.
dataSourceUserID | Specifies the user ID that you need to connect to the data source.
dataSourcePassword | Specifies the password that you need to connect to the data source.
exportTableName | Specifies the name of the table you want to export to in the data source.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.


crPEGetGraphOptions

The crPEGetGraphOptions function identifies the display options that are set for the specified graph in the specified section. Use this function to obtain information about any of several graph options. These options include the minimum and maximum values that can appear on the graph, whether grid lines appear, whether risers are labeled, whether bar graphs have horizontal or vertical bars, and whether a legend appears on the graph.

Declare Function crPEGetGraphOptions Lib "crwrap32.dll" Alias "crvbPEGetGraphOptions" (ByVal printJob As Integer, ByVal sectionCode As Integer, ByVal GraphN As Integer, ByRef GraphMaxValue As Double, ByRef GraphMinValue As Double, ByRef ShowDataValue As Long, ByRef ShowGridLine As Long, ByRef VerticalBars As Long, ByRef ShowLegend As Long, ByRef FontFaceName As String) As Integer

Parameters

printJob | Specifies the handle of the print job from which you want to get information about a graph.
sectionCode | Specifies the code for the report section in which the graph appears. See the table of section constants supplied in Working with section codes.
GraphN | Specifies which graph within the section you want information about. This value is 0 indexed. Within a section, graphs are numbered from top to bottom first, then from left to right if they have the same top.
GraphMaxValue | Specifies the maximum value that will appear in any graph. Any graph values above this value are not charted.
GraphMinValue | Specifies the minimum value that will appear in any graph. Any graph values below this value are not charted.
ShowDataValue | Specifies whether or not to display the numerical value associated with each riser on the chart. If set to TRUE (1), a value appears in the graph for each riser.
ShowGridLine | Specifies whether or not to display grid lines on the graph.
VerticalBars | Specifies whether to display the bars in a bar graph vertically or horizontally.
ShowLegend | Specifies whether or not to display the graph legend.
FontFaceName | Specifies the font face for all text and values in the entire graph.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.


crPEGetNthParameterType

VB Sample Code for modifying parameter fields

The crPEGetNthParameterType function returns the type of value one of the parameter fields in the specified report is expecting.

Declare Function crPEGetNthParameterType Lib "crwrap32.dll" (ByVal printJob As Integer, ByVal parameterN As Integer) As Integer

Parameters

printJob | Specifies the handle of the print job that contains the parameter field about which you want to retrieve information.
parameterN | Specifies the data type of the parameter field. Constants defined for the available parameter types are given in the following table:
Constant | Value
PE_PF_Number | 0
PE_PF_Currency | 1
PE_PF_Boolean | 2
PE_PF_Date | 3
PE_PF_String | 4

Return Value

TRUE (1) if the call is successful; FALSE (0) if the call fails.


crPEGetNthParameterField

The crPEGetNthParameterField function returns information about one of the parameter fields in the specified report: that is, it returns the name of the field, the data type, and information about the value set for the field.

Declare Function crPEGetNthParameterField Lib "crwrap32.dll" Alias "crvbPEGetNthParameterField" (ByVal printJob As Integer, ByVal parameterN As Integer, ByRef ValueType As Integer, ByRef DefaultValueSet As Integer, ByRef CurrentValueSet As Integer, ByRef Name As String, ByRef Prompt As String, ByRef DefaultValue As Any, ByRef CurrentValue As Any) As Integer

Parameters

printJob | Specifies the handle of the print job that contains the parameter field about which you want to retrieve information.
parameterN | Specifies the number of the parameter field about which you want to retrieve information.
ValueType | Specifies the data type of the parameter field. The Crystal Report Engine supports the following data types: number, currency, Boolean, date, and string. Use the appropriate constant from the list below.
Data Type | Constant
Number | PE_PF_NUMBER
Currency | PE_PF_CURRENCY
Boolean | PE_PF_BOOLEAN
Date | PE_PF_DATE
String | PE_PF_STRING

DefaultValueSet

Indicates whether or not a default value was set for the parameter field when the parameter field was created or modified in Crystal Reports. The value can be either TRUE (1) if the field was given a default value or FALSE (0) if it was not.

CurrentValueSet

Before PEStartPrintJob is called, this value indicated whether or not the user is prompted for a parameter field value. A value of 0 means they will be prompted; a value of 1 means they will not be prompted.

This value will contain 1 before PEStartPrintJob is called if:

the report contains saved data, or

crPESetNthParameterField has been called.

If PEStartPrintJob has been called, and the user has entered a parameter and said OK to the prompt, this parameter will equal 1 (TRUE) if the user enters a value at the prompt and 0 (FALSE) if the user clicks Cancel.

Return Value

TRUE (1) if the call is successful; FALSE (0) if the call fails.


crPEGetNthTableLocation

The crPEGetNthTableLocation function determines the location of a selected table used in the specified print job. This function is typically combined with crPESetNthTableLocation to identify the location of a table and then to change it.

Declare Function crPEGetNthTableLocation Lib "crwrap32.dll" Alias "crvbPEGetNthTableLocation" (ByVal printJob As Integer, ByVal TableN As Integer, ByRef tableLocation As String) As Integer

Parameters

printJob | Specifies the handle of the print job from which you want to retrieve information about a table's location.
TableN | Specifies the number of the table for which you want to retrieve location information. The first table is table 0.
tableLocation | Specifies the table location. This parameter is database dependent and must be formatted correctly for the expected database. For example: xBase (Natively): <drive>:\<path>\<file> xBase (ODBC): <data source name> Paradox (Natively): <drive>:\<path>\<file> Paradox (ODBC): <data source name> Btrieve (Natively): <drive>:\<path>\<file> Btrieve (ODBC): <data source name> Oracle (Natively): <database>.<table> Oracle (ODBC): <database>.<table> SQL Server (Natively): <database>.<owner>.<table> SQL Server (ODBC): <database>.<owner>.<table>

Return Value

TRUE (1) if the call is successful; FALSE (0) if the call fails.


crPEGetNthTableLogOnInfo

The crPEGetNthTableLogOnInfo function retrieves the log on information required by a report.

Declare Function crPEGetNthTableLogOnInfo Lib "crwrap32.dll" Alias "crvbPEGetNthTableLogOnInfo" (ByVal printJob As Integer, ByVal TableN As Integer, ByRef ServerName As String, ByRef dbName As String, ByRef UserID As String) As Integer

Parameters

printJob | Specifies the handle of the print job for which you want to get table log on information.
TableN | Specifies the number of the table from which you want to get log on information. The first table is table 0.
ServerName | Specifies the logon name for the server used to create the report. For ODBC, use the data source name. *
dbName | Specifies the logon name for the database used to create the report. *
UserID | Specifies the user ID# necessary to log on to the server. *
*When you pass an empty string ("") for this parameter, the program uses the value that's already set in the report. If you want to override a value that's already set in the report, use a non-empty string (i.e., "Server A"). All strings must be null-terminated.

Return Value

TRUE (1) if the call is successful; FALSE (0) if the call fails.


crPEGetNthTableSessionInfo

The crPEGetNthTableSessionInfo function gets the session information for a Microsoft Access table being used in your report. Many Microsoft Access database tables require that a session be opened before the information in the table can be used. Use crPEGetNthTableSessionInfo to obtain the session information (User ID, Password, and Session Handle) for a particular table.

Declare Function crPEGetNthTableSessionInfo Lib "crwrap32.dll" Alias "crvbPEGetNthTableSessionInfo" (ByVal printJob As Integer, ByVal TableN As Integer, ByRef UserID As String, ByRef SessionHandle As Long) As Integer

Parameters

printJob | Identifies the handle of the print job that uses the table for which you need to obtain the session information.
TableN | 0 indexed table number indicating which table in the report you wish to obtain the session information for.
UserID | Specifies the user ID value needed for logging on to the system.
SessionHandle | Specifies the handle to the current Microsoft Access session.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.

Remarks
  • This function is only applicable for Microsoft Access databases which require a session to be opened before the database is accessed.


crPEGetSelectedPrinter

If the printer has been specified in Crystal Reports using the File|Printer Setup|Specific printer option, the crPEGetSelectedPrinter function will return information about that printer if the same driver is installed on the machine. If the driver has not been installed on the machine, it will return information about the default printer specified in the Printers Window of the Control Panel.

Declare Function crPEGetSelectedPrinter Lib "crwrap32.dll" Alias "crvbPEGetSelectedPrinter" (ByVal printJob As Integer, ByRef driverName As String, ByRef printerName As String, ByRef portName As String, crmode As crDEVMODE) As Integer

Parameters

printJob | Specifies the handle to the print job that you want to query to get information on the non-default printer that has been selected with the report.
driverName | Specifies the name of the printer driver for the printer that is selected with the print job.
printerName | Specifies the name of the printer that is selected with the print job.
portName | Specifies the name of the port to which the selected printer is connected.
crmode | Specifies the crDEVMODE structure.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.


crPELogOffServer

The crPELogOffServer function logs off the specified server. Use any time you have to log off a specified server.

Declare Function crPELogOffServer Lib "crwrap32.dll" (ByVal DLLName As String, ByVal ServerName As String, ByVal dbName As String, ByVal UserID As String, ByVal Password As String) As Integer

Parameters

DLLName | Specifies the name of the Crystal Reports DLL for the data source you want to log off, for example, PDSODBC.DLL. Note that the DLLName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases, PDS*.DLL for SQL/ODBC databases.
ServerName | Specifies the logon name for the server used to create the report. For ODBC, use the data source name. *
dbName | Specifies the logon name for the database used to create the report. *
UserID | Specifies the user ID# necessary to log on to the server. *
Password | Specifies the password necessary to log on to the server.
*When you pass an empty string ("") for this parameter, the program uses the value that's already set in the report. If you want to override a value that's already set in the report, use a non-empty string (i.e., "Server A"). All strings must be null-terminated.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.

Remarks
  • crPELogOnServer and crPELogOffServer can be called at any time to log on and off a database server. These functions are not required if the function crPESetNthTableLogOnInfo was already used to log on to a table.
  • This function requires a database DLL name which can be retrieved using PEGetNthTableType.


crPELogOnServer

The crPELogOnServer function logs on to the specified server.

Declare Function crPELogOnServer Lib "crwrap32.dll" (ByVal DLLName As String, ByVal ServerName As String, ByVal dbName As String, ByVal UserID As String, ByVal Password As String) As Integer

Parameters

DLLName | Specifies the name of the Crystal Reports DLL for the data source you want to log on to, for example, PDSODBC.DLL. Note that the DLLName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases, PDS*.DLL for SQL/ODBC databases.
ServerName | Specifies the logon name for the server used to create the report. For ODBC, use the data source name. *
dbName | Specifies the logon name for the database used to create the report. *
UserID | Specifies the user ID# necessary to log on to the server. *
Password | Specifies the password necessary to log on to the server.
*When you pass an empty string ("") for this parameter, the program uses the value that's already set in the report. If you want to override a value that's already set in the report, use a non-empty string (i.e., "Server A"). All strings must be null-terminated.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.

Remarks
  • crPELogOnServer and crPELogOffServer can be called at any time to log on and off a database server. These functions are not required if the function crPESetNthTableLogOnInfo was already used to set the password for a table.
  • This function requires a database DLL name, which can be retrieved using PEGetNthTableType.
  • This function can also be used for non-SQL tables, such as password-protected Paradox tables. Call this function to set the password for the Paradox DLL before beginning printing.
  • When printing using PEStartPrintJob, the ServerName passed in PELogOnServer must agree exactly with the server name stored in the report. If this is not true, use crPESetNthTableLogOnInfo to perform logging on instead.
  • The following points need to be considered when deciding whether to use crPELogOnServer or crPESetNthTableLogOnInfo:
      • crPELogOnServer is easier to call than crPESetNthTableLogOnInfo and it can be called at any time. You must know the database DLL name to make this call, however.
      • crPESetNthTableLogOnInfo is more flexible than crPELogOnServer. It allows you to override any of the log on parameters. This call must be called after PEOpenPrintJob.
  • The 16-bit file name is needed for 32-bit. This represents the internal name of the file.


crPESelectPrinter

The crPESelectPrinter function specifies a printer other than the default printer as a print destination. You can use this function to enable the user to select a printer other than the default printer at print time. One way of doing this is to have your application call the common printer selection dialog box.

Declare Function crPESelectPrinter Lib "crwrap32.dll" (ByVal printJob As
Integer, ByVal driverName As String, ByVal printerName As String, ByVal
portName As String, crmode As crDEVMODE) As Integer
Parameters

printJob | Specifies the handle to the print job for which you want to select a printer.
driverName* | Specifies a pointer to a null-terminated string that contains the name of the printer driver for the selected printer.
printerName* | Specifies a pointer to a null-terminated string that contains the printer name for the selected printer.
portName* | Specifies a pointer to a null-terminated string that contains the port name for the port to which the selected printer is attached.
mode* | Specifies the crDEVMODE structure.
*The PRINTDLG structure, returned by the Windows API PrintDlg function, contains handles to crDEVMODE and DEVNAMES structures. This information can be used to obtain driverName, printerName, portName, and mode values for crPESelectPrinter.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.

Remarks
  • Your code must parse the return from the dialog box selection and insert the returned driverName, printerName, and portName as parameters in the call.
  • After selecting the printer with this call, you can direct the output to that printer (using the PEOutputToPrinter call) or to the print window (using the PEOutputToWindow call).
  • This call will override a printer selection that you built into the report at design time via the Select Printer menu command.
  • If you follow this call with the PEOutputToWindow call, the report appears in the Print Window formatted for the selected printer.
  • To revert to the default printer, pass zeros (0) for each parameter.
  • The driver name and printer name must exist on your machine.
  • You can specify a different printer port than that assigned to the selected printer on your machine.
  • For mode, use 0 for the default mode or create a crDEVMODE structure to customize (if your development tool supports such a structure.) For additional information on DEVMODE structures, see the documentation that comes with the Microsoft Windows Software Development Kit (SDK).


crPESetGraphOptions

The crPESetGraphOptions function changes the display options set for the specified graph in the specified section. Use this function to change any of several graph options. These options include the minimum and maximum values that can appear on the graph, whether grid lines appear, whether risers are labeled, whether bar graphs have horizontal or vertical bars, and whether a legend appears on the graph.

Declare Function crPESetGraphOptions Lib "crwrap32.dll" (ByVal printJob
As Integer, ByVal sectionCode As Integer, ByVal GraphN As Integer, ByVal
GraphMaxValue As Double, ByVal GraphMinValue As Double, ByVal
ShowDataValue As Long, ByVal ShowGridLine As Long, ByVal VerticalBars As
Long, ByVal ShowLegend As Long, ByVal FontFaceName As String) As Integer
Parameters

printJob | Specifies the handle of the print job for the report containing the graph you are changing.
sectionCode | Specifies the code for the report section in which the graph appears. See the table of section constants supplied in the Working with section codes topic.
GraphN | Specifies which graph within the section you want to change. This value is 0 indexed. Within a section, graphs are numbered from top to bottom, first, then from left to right if they have the same top.
GraphMaxValue | Specifies the maximum value that will appear in the graph. Any graph values above this value are not charted.
GraphMinValue | Specifies the minimum value that will appear in the graph. Any graph values below this value are not charted.
ShowDataValue | Specifies whether or not to display the numerical value associated with each riser on the chart. If set to TRUE (1), a value appears in the graph for each riser.
ShowGridLine | Specifies whether or not to display grid lines on the graph.
VerticalBars | Specifies whether to display the bars in a bar graph vertically or horizontally.
ShowLegend | Specifies whether or not to display the graph legend.
FontFaceName | Specifies the font for all text and values in the entire graph.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.


crPESetNthParameterField

The crPESetNthParameterField function sets a value for the specified parameter field.

Declare Function crPESetNthParameterField Lib "crwrap32.dll" (ByVal printJob As Integer, ByVal parameterN As Integer, ByVal ValueType As Integer, ByVal DefaultValueSet As Integer, ByVal CurrentValueSet As Integer, ByVal Name As String, ByVal Prompt As String, ByRef DefaultValue As Any, ByRef CurrentValue As Any) As Integer

Parameters

printJob | Specifies the handle of the print job for which you want to set a parameter field value.
parameterN | Specifies the number of the parameter field in the report.
ValueType | Specifies the data type of the parameter field. The Crystal Report Engine supports the following data types: number, currency, Boolean, date, and string. Use the appropriate constant from the list below.
Data Type | Constant
Number | PE_PF_NUMBER
Currency | PE_PF_CURRENCY
Boolean | PE_PF_BOOLEAN
Date | PE_PF_DATE
String | PE_PF_STRING

DefaultValueSet

Indicates whether or not to use the default value for the parameter field. The value can be either TRUE (1) to use the default value or FALSE (0) to specify a new value.

Return value

TRUE (1) if the call is successful, FALSE (0) if the call fails.


crPESetNthTableLocation

The crPESetNthTableLocation function sets the location for a selected table in the specified print job. This function is typically combined with crPEGetNthTableLocation to identify the location of a table and then to change it.

Declare Function crPESetNthTableLocation Lib "crwrap32.dll" (ByVal printJob As Integer, ByVal TableN As Integer, ByVal tableLocation As String) As Integer

Parameters

printJob | Specifies the handle of the print job for which you want to set a table's location.
TableN | Specifies the number of the table for which you want to set a new location.
tableLocation | Specifies the location of the table.

Return Value

TRUE (1) if the call is successful; FALSE (0) if the call fails.


crPESetNthTableLogOnInfo

The crPESetNthTableLogOnInfo function sets the log on information for the specified print job.

Declare Function crPESetNthTableLogOnInfo Lib "crwrap32.dll" (ByVal printJob As Integer, ByVal TableN As Integer, ByVal ServerName As String, ByVal dbName As String, ByVal UserID As String, ByVal Password As String, ByVal PropagateAcrossTables As Long) As Integer

Parameters

printJob | Specifies the handle of the print job for which you want to set table log on information.
TableN | Specifies the number of the table for which you want to set log on information. The first table is table 0. The last table is N-1.
ServerName | Specifies the logon name for the server used to create the report. For ODBC, use the data source name. *
dbName | Specifies the logon name for the database used to create the report. *
UserID | Specifies the user ID# necessary to log on to the server. *
Password | Specifies the password necessary to log on to the server.
PropagateAcrossTables | Indicates whether or not the program should apply the new log on information to any other tables in the report that had the same original server and database names as the specified table. You may use either of the following values:
Value | Meaning
TRUE | Program will apply log on information to all other tables that have the same original server and database names.
FALSE | Program will update only the selected table.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.

Remarks
  • The program logs on when printing the report, but you must first set the correct log on information using crPESetNthTableLogOnInfo.
  • You must supply at least the password with this function with empty strings for the other parameters. Additionally, you can change the server, database, and/or user name by entering the appropriate values.
  • Logging off is performed automatically when the print job is closed.
  • crPESetNthTableLogOnInfo allows you to override any of the log on parameters.
  • When you create a report off a single database (for example, one MDB file with multiple tables), set the PropagateAcrossTables parameter to TRUE. This insures that the changes are made to all tables in the MDB file (thus avoiding the necessity to code the changes for each table individually).


crPESetNthTableSessionInfo

The crPESetNthTableSessionInfo function sets the specified session information when opening a Microsoft Access table. Many Microsoft Access database tables require that a session be opened before the table can be used. Use crPESetNthTableSessionInfo to open the session.

Declare Function crPESetNthTableSessionInfo Lib "crwrap32.dll" (ByVal printJob As Integer, ByVal TableN As Integer, ByVal UserID As String, ByVal Password As String, ByVal SessionHandle As Long, ByVal PropagateAcrossTables As Long) As Integer

Parameters

printJob | Specifies the handle of the print job for which you want to change the Microsoft Access session information.
TableN | 0 based table number specifying which table the session is being opened for.
UserID | Specifies the user ID# necessary to log on to the system.
Password | Specifies the password needed for logging on to the system.
SessionHandle | The handle to the current Microsoft Access session.
PropagateAcrossTables | TRUE or FALSE value indicating whether the session information should be used for opening all tables being used in the report.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.

Remarks
  • This function is only applicable for secured Microsoft Access databases which require a session to be opened before the database is accessed.


crPEYearMonthDayToDate

The crPEYearMonthDayToDate function takes a Year, Month, and Day value and combines them into a single Date value.

Declare Function crPEYearMonthDayToDate Lib "crwrap32.dll" (ByVal nYear As Integer, ByVal nMonth As Integer, ByVal nDay As Integer) As Long

Parameters

nYear | Specifies the year value.
nMonth | Specifies the month value.
nDay | Specifies the day value.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.


crvbHandleToBStr

The crvbHandleToBstr function will obtain a string from a string handle returned by any Crystal Report Engine function that returns a variable length string. For more information on variable length strings, see Crystal Report Engine API variable length strings.

Declare Function crvbHandleToBStr Lib "crwrap32.dll" (ByRef BString As String, ByVal strHandle As Long, ByVal strLength As Integer) As Integer

Parameters

BString | The actual string pointed to by the string handle.
strHandle | The string handle returned by the variable length string function.
strLength | The length of the string pointed to by the string handle.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.


PEGetGraphOptions4

The PEGetGraphOptions4 function was specially designed to accept VB's native 4-byte aligned "Types." It identifies the display options that are set for the specified graph in the specified section. Use this function to obtain information about any of several graph options. These options include the minimum and maximum values that can appear on the graph, whether grid lines appear, whether risers are labeled, whether bar graphs have horizontal or vertical bars, and whether a legend appears on the graph.

Declare Function PEGetGraphOptions4 Lib "crwrap32.dll" (ByVal printJob
As Integer, ByVal sectionCode As Integer, ByVal GraphN As Integer,
GraphOptions As PEGraphOptions4) As Integer
Parameters

printJob | Specifies the handle of the print job from which you want to get information about a graph.
sectionCode | Specifies the code for the report section in which the graph appears. See the table of section constants supplied with Working with section codes.
GraphN | Specifies which graph within the section you want information about. This value is 0 indexed. Within a section, graphs are numbered from top to bottom first, then from left to right if they have the same top.
GraphOptions | Specifies the pointer to the PEGraphOptions4 structure.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.


PEGetJobStatus4

The PEGetJobStatus4 function was specially designed to accept VB's native 4-byte aligned "Types." It evaluates the status of a print job. You can use this function in a number of programming situations, for example:

  • to trigger error messages when a print job fails due to insufficient memory, insufficient disk space, etc.,
  • to trigger screen displays (hourglass, series of graphics, etc.) that confirm to the user that work is in progress, or
  • to find out whether a job was canceled by the user after PEStartPrintJob returns.
Declare Function PEGetJobStatus4 Lib "crwrap32.dll" (ByVal printJob As
Integer, JobInfo As PEJobInfo4) As Integer
Parameters

printJob | Specifies the handle of the print job for which you want to determine printing status.
JobInfo | Specifies a pointer to the PEJobInfo4 structure that will capture the information this function retrieves.

Returns
  • 0 if PEOpenEngine or PEOpenPrintJob has not been called successfully.
  • 1 if the job has not started yet (PE_JOBNOTSTARTED).
  • 2 if the job is in progress (PE_JOBINPROGRESS).
  • 3 if the job has completed successfully (PE_JOBCOMPLETED).
  • 4 if the job has failed (PE_JOBFAILED).
  • 5 if the job has been canceled by the user (PE_JOBCANCELLED).
  • 6 if the report has exceeded the record or time governors (PE_JOBHALTED).


PEGetNthTableSessionInfo4

The PEGetNthTableSessionInfo4 function was specially designed to accept VB's native 4-byte aligned "Types." It gets the session information for a Microsoft Access table being used in your report. Many Microsoft Access database tables require that a session be opened before the information in the table can be used. Use PEGetNthTableSessionInfo4 to obtain the session information (User ID, Password, and Session Handle) for a particular table.

Declare Function PEGetNthTableSessionInfo4 Lib "crwrap32.dll" (ByVal
printJob As Integer, ByVal TableN As Integer, SessionInfo As
PESessionInfo4) As Integer
Parameters

printJob | Identifies the handle of the print job that uses the table for which you need to obtain the session information.
TableN | 0 indexed table number indicating which table in the report you wish to obtain the session information for.
SessionInfo | Refer to the PESessionInfo4 structure for further information.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.

Remarks
  • This function is only applicable for Microsoft Access databases which require a session to be opened before the database is accessed.


PEGetNthTableType4

The PEGetNthTableType4 function was specially designed to accept VB's native 4-byte aligned "Types." It allows the application to determine the type of each table.

Declare Function PEGetNthTableType4 Lib "crwrap32.dll" (ByVal printJob
As Integer, ByVal TableN As Integer, TableType As PETableType4) As
Integer
Parameters

printJob | Specifies the handle of the print job for which you want to determine a table type.
TableN | Specifies the number of the table for which you want to determine the type. Table numbers start at 0.
TableType | Specifies the pointer to the PETableType4 structure.

Return Value

TRUE (1) if the call is successful, FALSE (0) if anything goes wrong.

Remarks

The application can test DBType in thePETableType4 structure, or test the database DLL name used to create the report. DLL names have the following naming convention:

  • PDB*.DLL for standard (non-SQL) databases, and
  • PDS*.DLL for SQL/ODBC databases.
      • In the case of ODBC (PDSODBC.DLL) the DescriptiveName includes the ODBC data source name.

        All strings must be null-terminated.

You must initialize this member to be the size of whatever it is. For example:

tableType.StructSize = PE_SIZEOF_TABLE_TYPE


PELogOffServer4

The PELogOffServer4 function was specially designed to accept VB's native 4-byte aligned "Types." It logs off the specified server. Use any time you have to log off a specified server.

Declare Function PELogOffServer4 Lib "crwrap32.dll" (ByVal DLLName As
String, LogOnInfo As PELogOnInfo4) As Integer
Parameters

DLLName | Specifies the name of the Crystal Reports DLL for the data source you want to log off, for example, PDSODBC.DLL. Note that the DLLName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases, PDS*.DLL for SQL/ODBC databases.
LogOnInfo | Specifies the pointer to the PELogOnInfo4 structure.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.

Remarks
  • PELogOnServer4 and PELogOffServer4 can be called at any time to log on and off a database server. These functions are not required if the function crPESetNthTableLogOnInfo was already used to log on to a table.
  • This function requires a database DLL name which can be retrieved using PEGetNthTableType.


PELogOnServer4

The PELogOnServer4 function was specially designed to accept VB's native 4-byte aligned "Types." It logs on to the specified server.

Declare Function PELogOnServer4 Lib "crwrap32.dll" (ByVal DLLName As
String, LogOnInfo As PELogOnInfo4) As Integer
Parameters

DLLName | Specifies the name of the Crystal Reports DLL for the server or password protected non-SQL table you want to log on to, for example, PDSODBC.DLL. Note that the DLLName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases, PDS*.DLL for SQL/ODBC databases.
LogOnInfo | Specifies the pointer to the PELogOnInfo4 structure.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.

Remarks
  • PELogOnServer4 and PELogOffServer4 can be called at any time to log on and off a database server. These functions are not required if the function crPESetNthTableLogOnInfo was already used to set the password for a table.
  • This function requires a database DLL name, which can be retrieved using PEGetNthTableType.
  • This function can also be used for non-SQL tables, such as password-protected Paradox tables. Call this function to set the password for the Paradox DLL before beginning printing.
  • When printing usingPEStartPrintJob, the ServerName passed in PELogOnServer must agree exactly with the server name stored in the report. If this is not true, use crPESetNthTableLogOnInfo to log on instead.
  • The 16-bit file name is needed for 32-bit. This represents the internal name of the file.


PESetGraphOptions4

The PESetGraphOptions4 function was specially designed to accept VB's native 4-byte aligned "Types." It changes the display options set for the specified graph in the specified section. Use this function to change any of several graph options. These options include the minimum and maximum values that can appear on the graph, whether grid lines appear, whether risers are labeled, whether bar graphs have horizontal or vertical bars, and whether a legend appears on the graph.

Declare Function PESetGraphOptions4 Lib "crwrap32.dll" (ByVal printJob
As Integer, ByVal sectionCode As Integer, ByVal GraphN As Integer,
GraphOptions As PEGraphOptions4) As Integer
Parameters

printJob | Specifies the handle of the print job for the report containing the graph you are changing.
SectionCode | Specifies the code for the report section in which the graph appears. See the table of section constants supplied in the Working with section codes topic.
GraphN | Specifies which graph within the section you want to change. This value is 0 indexed. Within a section, graphs are numbered from top to bottom, first, then from left to right if they have the same top.
GraphOptions | Specifies the pointer to the PEGraphOptions4 structure.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.


PESetNthTableSessionInfo4

The PESetNthTableSessionInfo4 function was specially designed to accept VB's native 4-byte aligned "Types." It sets the specified session information when opening a Microsoft Access table. Many Microsoft Access database tables require that a session be opened before the table can be used. Use PESetNthTableSessionInfo4 to open the session.

Declare Function PESetNthTableSessionInfo4 Lib "crwrap32.dll" (ByVal
printJob As Integer, ByVal TableN As Integer, SessionInfo As
PESessionInfo4, ByVal PropagateAcrossTables As Long) As Integer
Parameters

printJob | Specifies the handle of the print job for which you want to change the Microsoft Access session information.
TableN | 0 based table number specifying which table the session is being opened for.
SessionInfo | Refer to the PESessionInfo4 structure for further information.
PropagateAcrossTables | TRUE or FALSE value indicating whether the session information should be used for opening all tables being used in the report.

Return Value

TRUE (1) if the call is successful, FALSE (0) if the call fails.

Remarks
  • This function is only applicable for secured Microsoft Access databases which require a session to be opened before the database is accessed.


Crystal Report Engine Object Model
for the Automation Server

The Crystal Report Engine Object Library provides an object oriented approach for programming the Crystal Reports Engine in your application. In this section you will find detailed information on objects and collections, along with their associated properties, methods, and events.

Click the appropriate link to jump to that section:

  • Overview of the Crystal Report Engine Object Model
  • Crystal Report Engine Object Model Reference
  • FormulaFieldDefinition Object
  • Error Codes


Overview of the Crystal Report Engine Object Model

Object Hierarchy

The Crystal Report Engine Object Model for the Crystal Report Engine Automation Server provides all of the power of the Crystal Report Engine in an easy to use object-oriented hierarchy. The following diagram illustrates this object hierarchy:

Object Naming Conflicts

If your project includes other libraries that contain objects named identically to those found in the Crystal Report Engine Object Model, you will encounter conflicts unless you reference the objects by using a prefix. For example, if you have included the DAO Library with the Crystal Report Engine Object Model in your project, both libraries include a Database Object. In order to avoid conflicts, you must prefix the objects as follows:

CRPEAuto.Database

for the Crystal Report Engine Object Model, or

DAO.Database

for the DAO Library.

Note: You must always prefix when referencing the Font Object. Visual Basic includes a VB Font Object that is always included when creating a project, so conflicts will always occur unless the object is properly referenced.(For example, CRPEAuto.Font).

Object Model Events

Events are only available when using Visual Basic 5.0 or later. To use events, you must first declare the desired Object (Report or Window) as Public and With Events in the General, Declarations area of the module.

For example, declare the Report object as follows:

Public WithEvents reportVar As CRPEAuto.Report

The Visual Basic code screen will then list reportVar in the Object list, with events listed in the Procedure list. Adding code to an event will cause this code to be run whenever the event occurs, which in turn will be followed by the default behavior for the event. For complete information on handling events, see Handling preview window events.


Crystal Report Engine Object Model Reference

The rest of this section lists all objects in the Report Engine Object Model and describes their properties, methods, and events. Objects are listed in alphabetical order with a brief description and example of their use in Visual Basic code. A table follows each object description, listing all properties for the object, the purpose of each property, and whether the property is read only or both read and write. After each property table is a listing of object methods in alphabetical order. Finally, if an object supports events, the events are also listed in alphabetical order. Each method and event listing includes a complete description of its purpose and use inside Visual Basic. For more information on using the Report Engine Object Model in Visual Basic, see Enhancements to the Crystal Report Print Engine API.


Objects and Collections

Including Properties, Methods, and Events


Application Object

Sample Code - Creating an Application Object

The Application Object is the only creatable object in the Crystal Report Engine Object Model. All access to the Crystal Report Engine Automation Server must begin with the creation of an instance of the Application object.

An instance of the Application object can be created using the Visual Basic New keyword or using the CreateObject function and the Prog Id Crystal.CRPE.Application. However, the Visual Basic New keyword is much easier and more efficient to use. With New, you do not need to reference Crystal.CRPE.Application, which means that you can eliminate some unnecessary coding details.

For example,

  • Using the New keyword:
Dim app as Application

Set app = New Application

Or,
' Automatically creates a new instance of the object when it is first

' referenced in the code, so it doesn't have to be set.

Dim app As New Application
  • Using the CreateObject function:
Dim app As Object

Set app = CreateObject("Crystal.CRPE.Application")


Application Object Properties

Property | Description | Read/Write
LastErrorCode | Returns the most recent error code. Used for errors at the application level. | Read only
LastErrorString | Returns the most recent error string. Used for errors at the application level. | Read only
Options | Returns the GlobalOptions Object, which allows you to request more descriptive error messages from the Crystal Report Engine. | Read only
Parent | Returns a null object (Nothing) as Application has no parent. | Read only

Note: When any Visual Basic standard error is returned, LastErrorString will be empty.


Application Object Methods

Related topics:

CanClose Method (Application Object)

ClearError Method (Application Object)

LogOffServer Method (Application Object)

LogOnServer Method (Application Object)

OpenReport Method (Application Object)


CanClose Method (Application Object)

The CanClose method indicates whether or not the Application Object, can be destroyed. This method will return FALSE as long as there are valid Report objects in existence. The Application object can be destroyed only if no instances of the Report Object, exist.

Syntax
object.CanClose
Returns
  • TRUE if the Engine can be closed.
  • FALSE if the Engine is busy.


ClearError Method (Application Object)

The ClearError method clears the application error code and string stored when calling the LastErrorCode and LastErrorString properties.

Syntax

object.ClearError


LogOffServer Method (Application Object)

The LogOffServer method logs off an SQL server or ODBC data source. Use this method when you have logged on to the data source by using LogOnServer Method (Application Object).

Syntax

object.LogOffServer DLLName, ServerName, DatabaseName, UserID, Password

Parameters
DLLName | Specifies the name of the DLL for the server or password-protected non-SQL table that you want to log on to (for example, "PDSODBC.DLL"). Note that the DLLName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases, PDS*.DLL for SQL/ODBC databases.
ServerName | Specifies the logon name for the server used to create the report.* (For ODBC, use the data source name.) This value is case-sensitive.
DatabaseName (Optional) | Specifies the name for the database used to create the report.*
UserID (Optional) | Specifies the User ID number necessary to log on to the server.*
Password (Optional) | Specifies the password necessary to log on to the server.

*When you pass an empty string ("") for this parameter, the program uses the value that is already set in the report. If you want to override a value that is already set in the report, use a non-empty string (for example, "Server A").

Remarks

If you try to log off a server that is still in use (that is, there is an object variable still in focus that holds reference to a report that requires being logged on to the server to access data) you will be unable to log off. This will apply to every object that comes from the Report Object, as they all hold reference to the report through their respective Report properties.


LogOnServer Method (Application Object)

The LogOnServer method logs on to an SQL server or ODBC data source. Once logged on by using this method, you will remain logged on until you call LogOffServer Method (Application Object), or until the Application Object, is destroyed. This method corresponds to PELogOnServer, of the Crystal Report Engine API.

Syntax

object.LogOnServer DLLName, ServerName, DatabaseName, UserID, Password

Parameters
DLLName | Specifies the name of the DLL for the server or password-protected non-SQL table that you want to log on to (for example, "PDSODBC.DLL"). Note that the DLLName must be enclosed in quotes. DLL names have the following naming convention: PDB*.DLL for standard (non-SQL) databases, PDS*.DLL for SQL/ODBC databases.
ServerName | Specifies the logon name for the server used to create the report.* (For ODBC, use the data source name.) This value is case-sensitive.
DatabaseName (Optional) | Specifies the name for the database used to create the report.*
UserID (Optional) | Specifies the User ID number necessary to log on to the server.*
Password (Optional) | Specifies the password necessary to log on to the server.

*When you pass an empty string ("") for this parameter, the program uses the value that is already set in the report. If you want to override a value that is already set in the report, use a non-empty string (for example, "Server A").


OpenReport Method (Application Object)

Sample Code - OpenReport Method

The OpenReport method opens an existing report file, creating an instance of the Report object. Through the Report Object, you can change formatting, formulas, selection formulas, and sort fields for the report, then print, preview, or export the report. This method corresponds to PEOpenPrintJob, of the Crystal Report Engine API.

Syntax
Dim rep As Report

Set rep = app.OpenReport(ReportFilePath)
Parameters

ReportFilePath

Specifies a string value indicating the file name and path of the report that you want to open.

Returns
  • Returns an instance of the Report Object, if the report was successfully opened.
  • Returns 0 if the report file does not exist or if an error occurs.


Area Object

Sample Code - Area Object

The Area Object represents an area in a report. An area is a group of like sections in the report (for example, Details A - Da, Details B - Db, etc.) that all share the same characteristics. Each section within the area can be formatted differently. This object allows you to retrieve information and set options for a specified area in your report.

Area Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
CopiesToPrint | Returns/Sets the number of copies of each item in the Details section of the report. For example, by default, each line of the Details section only prints once. By setting this to 3, each line of the Details section would print 3 times. | Read/Write
GroupNumber | If the area is a group, this returns the group number. Otherwise, exception is thrown. | Read only
GroupOptions | Returns GroupAreaOptions Object, which provides properties/methods for getting and setting group options. Exception is thrown if area is not a group area. | Read only
Kind | Returns CRAreaKind (see table below), which specifies what "kind" of area (that is, Details, Report Header, Page Footer, etc.). | Read only
 | Constant | Value
 | crDetail | 4
 | crGroupFooter | 5
 | crGroupHeader | 3
 | crPageFooter | 7
 | crPageHeader | 2
 | crReportFooter | 8
 | crReportHeader | 1
Property | Description | Read/Write
Options | Returns AreaOptions Object, which provides properties for getting and setting area options (that is, new page before, keep together, etc.). | Read only
Parent | Reference to the Parent object (Area Object). | Read only
Report | Reference to Report Object. | Read only
Sections | Returns Sections Collection, which specifies a collection of all the sections in the area. | Read only


AreaOptions Object

The AreaOptions object allows you to retrieve information and set options for a specified area of your report (that is, new page before, keep together, underlay section, etc.). An AreaOptions object is obtained from the Options property of the Area Object.

Each report area is comprised of sections which can be formatted independently of each other by using the SectionOptions Object. These section options are combined with the options set by using the AreaOptions Object to make up the final appearance of a section and an area of the report. The settings in the AreaOptions object will affect all sections within the area, while settings in the SectionOptions object will affect only the section to which they are set.

If there is a conflict of settings between the AreaOptions object and the SectionOptions object, the object with an option set to TRUE will override the setting for the other object. For example, if the AreaOptions object has the KeepTogether property set to TRUE, all sections within the area will have KeepTogether applied, even if the SectionOptions object for a section has KeepTogether set to FALSE. If, however, the AreaOptions object has KeepTogether set to FALSE, but a section within that area has KeepTogether set to TRUE, that section will have the KeepTogether format option applied.

If an area has only a single section, all options will be combined between both the AreaOption object and the SectionOptions object. All TRUE settings set in either object will result in a TRUE setting for the entire area and section. While changing format options for areas and sections in reports, be sure to keep track of settings in both the AreaOptions and SectionOptions objects.


AreaOptions Properties

Property | Description | Read/ Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
KeepTogether | Returns/Sets Boolean value indicating if the values in this area are kept together across pages. | Read/Write
KeepTogether Formula | Returns/Sets string specifying a formula for conditionally setting when values in the area are kept together across pages. | Read/Write
NewPageAfter | Returns/Sets Boolean value indicating if a page break occurs just after this area. | Read/Write
NewPageAfter Formula | Returns/Sets string specifying a formula for conditionally setting when a page break occurs after the area. | Read/Write
NewPageBefore | Returns/Sets Boolean value indicating if a page break occurs just before this area. | Read/Write
NewPageBefore Formula | Returns/Sets string specifying a formula for conditionally setting when a page break occurs before the area. | Read/Write
NotHideForDrill Down | Returns/Sets Boolean value indicating if the area is not hidden for drill-down. | Read/Write
NotHideForDrill DownFormula | Returns/Sets string specifying a formula for conditionally setting when the area is not hidden for drill-down. | Read/Write
Parent | Reference to the Parent object (Area Object). | Read only
PrintAtBottomOf Page | Returns/Sets Boolean value indicating if the area is to appear at the bottom of the page. | Read/Write
PrintAtBottomOf PageFormula | Returns/Sets string specifying a formula for conditionally setting when the area is printed at the bottom of the page. | Read/Write
Report | Reference to Report Object. | Read only
ResetPageNumber After | Returns/Sets Boolean value indicating if the page number is reset to one after this area is printed. | Read/Write
ResetPageNumber AfterFormula | Returns/Sets string specifying a formula for conditionally setting when the page number should be reset after the area is printed. | Read/Write
Visible | Returns/Sets Boolean value indicating whether the report area is visible or not. | Read/Write
VisibleFormula | Returns/Sets string specifying a formula for conditionally setting when an area is visible. | Read/Write


Areas Collection

The Areas Collection contains a collection of area objects for every area in the report. Access a specific Area Object, in the collection using the Item property.

Areas Collection Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Count | Returns the number of areas in the collection. | Read only
Item | Returns Area Object. Item has an index parameter that can be either a string reference to the area (that is, "RH", "PH", "GHn", "D", "GFn", "PF", or "RF") or a numeric, 1-based index (that is, Item (1)) for the Report Header area. The items in the collection are indexed in the order that they are listed for each section/area. | Read only
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only

Remarks

Instead of using the Item property as shown, you can reference an area directly (for example, Areas ("RH") or Areas (1)).


BlobFieldObject Object

The BlobFieldObject Object allows you to get and set information for bitmap database fields in a report.

BlobFieldObject Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Field | Returns DatabaseFieldDefinition Object, containing information about the BLOB field. | Read only
Kind | Returns CRObjectKind object which specifies what "kind" of object (that is, box, cross-tab, field, etc.). | Read only
 | Constant | Value
 | crBlobFieldObject | 9
 | crBoxObject | 4
 | crCrossTabObject | 8
 | crFieldObject | 1
 | crGraphObject | 7
 | crLineObject | 3
 | crOleObject | 6
 | crSubreportObject | 5
 | crTextObject | 2
Property | Description | Read/Write
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only


BoxObject Object

The BoxObject object represents a box that has been drawn on the report. This object allows you to get information about boxes in a report.

BoxObject Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Kind | Returns CRObjectKind object, which specifies what "kind" of object (that is, box, cross-tab, field, etc.). | Read only
 | Constant | Value
 | crBlobFieldObject | 9
 | crBoxObject | 4
 | crCrossTabObject | 8
 | crFieldObject | 1
 | crGraphObject | 7
 | crLineObject | 3
 | crOleObject | 6
 | crSubreportObject | 5
 | crTextObject | 2
Property | Description | Read/Write
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only


CrossTabObject Object

The CrossTabObject Object allows you to get and set information for cross-tab objects in a report.

CrossTabObject Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Kind | Returns CRObjectKind object, which specifies what "kind" of object (that is, box, cross-tab, field, etc.). | Read only
 | Constant | Value
 | crBlobFieldObject | 9
 | crBoxObject | 4
 | crCrossTabObject | 8
 | crFieldObject | 1
 | crGraphObject | 7
 | crLineObject | 3
 | crOleObject | 6
 | crSubreportObject | 5
 | crTextObject | 2
Property | Description | Read/Write
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only
SummaryFields | Returns the SummaryFieldDefinitions Collection, providing access to information about all summary fields in the cross-tab object. | Read only


Database Object

Sample Code - Database Object

The Database Object provides properties to get information about the database accessed by a report. See Object Naming Conflicts.

Database Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Parameters | Returns DatabaseParameters Collection, which specifies the database parameters used in the report. | Read only
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only
Tables | Returns DatabaseTables Collection, which specifies the database objects used in the report (that is, an Access report may contain a query or an SQL Server report may be based on a stored procedure; if so, they will be returned as part of this collection, along with the database table used in the report). | Read only


Database Object Methods

Verify Method (Database Object)


Verify Method (Database Object)

The Verify method verifies that the location of the database is still valid and checks to see if any changes have been made to table design, etc. If there are any changes to the database, the Verify method will update the report automatically to reflect these changes.

Syntax

object.Verify


DatabaseFieldDefinition Object

The DatabaseFieldDefinition Object represents a database field used in the report. This object provides properties for getting information on database fields in the report.

Database FieldDefinition Object Properties

Property | Definition | Read/ Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
DatabaseField Name | Specifies the name of the field in the database (that is, Product ID). | Read only
Kind | Returns CRFieldKind, which specifies what "kind" of field (that is, database, summary, formula, etc.). | Read only
 | Constant | Value
 | crDatabaseField | 1
 | crFormulaField | 2
 | crGroupNameField | 5
 | crParameterField | 6
 | crSpecialVarField | 4
 | crSummaryField | 3
Property | Definition | Read/ Write
Name | Returns the name of the field within the report (table.FIELD) (for example, product.PRODUCT ID). | Read only
NumberOfBytes | Returns the number of bytes required to store the field data in memory. | Read only
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only
TableAliasName | Specifies the alias name used in the report to reference the database table. By default, this is the name of the database table. | Read only
ValueType | Returns CRFieldValueType (see table below) which specifies the "type" of value found in the field. | Read only
 | Constant | Value
 | crBitmapField | 17
 | crBlobField | 15
 | crBooleanField | 9
 | crChartField | 21
 | crCurrencyField | 8
 | crDateField | 10
 | crDateTimeField | 16
 | crIconField | 18
 | crInt16sField | 3
 | crInt16uField | 4
 | crInt32sField | 5
 | crInt32uField | 6
 | crInt8sField | 1
 | crInt8uField | 2
 | crNumberField | 7
 | crOleField | 20
 | crPersistentMemoField | 14
 | crPictureField | 19
 | crStringField | 12
 | crTimeField | 11
 | crTransientMemoField | 13
 | crUnknownField | 22


DatabaseFieldDefinitions Collection

The DatabaseFieldDefinitions Collection is a collection of database field definition objects. One object exists in the collection for every database field accessed by the report. Access a specific DatabaseFieldDefinition Object, in the collection by using the Item property.

Database FieldDefinitions Collection Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Count | The number of DatabaseFieldDefinition Object, in the collection. | Read only
Parent | Reference to the Parent object (DatabaseTable Object). | Read only
Report | Reference to Report Object. | Read only
Item | Returns DatabaseFieldDefinition Object. Item has an index parameter that can be either a string reference to the database field name or a numeric, 1-based index (that is, Item (1)) for the first database field in the collection. When a numeric index is used, the items in the collection are indexed in the order that they were added to the report. | Read only

Remarks

Instead of using the Item property as shown, you can reference a database directly (for example, DatabaseFieldDefinition("Product ID") or DatabaseFieldDefinition(1)).


DatabaseParameter Object

The DatabaseParameter Object specifies a stored procedure in an SQL database or an Access parameterized query.

Database Parameter Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Name | Returns the name of the parameter from the parameterized query/stored procedure that the report was created from. | Read only
Parent | Reference to the Parent object (Database Object). | Read only
Report | Reference to Report Object. | Read only
Type | Returns CRFieldValueType (see table below), which specifies the "type" of value found in the field. | Read only
 | Constant | Value
 | crBitmapField | 17
 | crBlobField | 15
 | crBooleanField | 9
 | crChartField | 21
 | crCurrencyField | 8
 | crDateField | 10
 | crDateTimeField | 16
 | crIconField | 18
 | crInt16sField | 3
 | crInt16uField | 4
 | crInt32sField | 5
 | crInt32uField | 6
 | crInt8sField | 1
 | crInt8uField | 2
 | crNumberField | 7
 | crOleField | 20
 | crPersistentMemoField | 14
 | crPictureField | 19
 | crStringField | 12
 | crTimeField | 11
 | crTransientMemoField | 13
 | crUnknownField | 22
Property | Description | Read/Write
Value | Returns/Sets the value for a database parameter as a string (that is, when you are setting a numeric parameter that you would use: DatabaseParameter.Value = "5"). | Read/Write


DatabaseParameters Collection

The DatabaseParameters Collection is a collection of database parameter objects. A DatabaseParameter object exists in the collection for every stored procedure parameter accessed by the report. Access a specific DatabaseParameter Object, in the collection by using the Item property.

DatabaseParameters Collection Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Count | Specifies the number of database parameters in the collection. | Read only
Item | Returns DatabaseParameter Object. Item has an index parameter that is a numeric, 1-based index (that is, Item (1)). The items in the collection are indexed in the order they were added to the report. | Read only
Parent | Reference to the Parent object (Database Object). | Read only
Report | Reference to Report Object. | Read only

Remarks

Instead of using the Item property as shown, you can reference a parameter directly (for example, DatabaseParameters(1)).


DatabaseTable Object

Sample Code - DatabaseTable Object

The DatabaseTable Object refers to a database table accessed by the report.

DatabaseTable Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Descriptive Name | Returns a descriptive name for the data source (i.e., Access table returns "Microsoft DAO Database DLL"). | Read only
DllName | Returns the name of the DLL used in the report (that is, PDBDAO.DLL, PDSODBC.DLL, etc.). | Read only
Fields | Returns DatabaseFieldDefinitions Collection, specifying a collection of database fields in the table. | Read only
Location | Gets/sets the location of the database table. | Read/Write
LogOnDatabase Name | Returns the name of the database if the database was logged on to. The format of this name will depend on the data source. | Read only
LogOnServer Name | Returns the name of the server that the database logged on to (for example, with ODBC reports, the ODBC data source name is returned). | Read only
LogOnUserID | Returns user ID used when logging on to the data source. | Read only
Name | Returns/Sets the alias name for the database table used in the report. | Read/Write
Parent | Reference to the Parent object (Database Object). | Read only
PrivateDataTag | This property contains information about the type of data accessed by the database driver. This value is used by the database driver for the data source and should not be used in your application. If your report has been designed by using the crystal active data driver (see Active Data), the PrivateDataTag property will contain a value of 3, once an active data source has been assigned to the report. This value is associated with GetPrivateData Method (DatabaseTable Object), and SetPrivateData Method (DatabaseTable Object), methods. | Read only
Report | Reference to Report Object. | Read only
SessionUserID | Returns the user ID used for Access session security. Returns the user ID used to create the report, or the user ID passed to the SetSessionInfo Method (DatabaseTable Object), method if an Access session has been opened. | Read only
Type | Returns value of type CRDatabaseType (see table below) indicating the type of database (that is, standard or SQL). | Read only
 | Constant | Value
 | crSQLDatabase | 2
 | crStandardDatabase | 1


DatabaseTable Object Methods

GetPrivateData Method (DatabaseTable Object)

SetLogOnInfo Method (DatabaseTable Object)

SetPrivateData Method (DatabaseTable Object)

SetSessionInfo Method (DatabaseTable Object)

TestConnectivity Method (DatabaseTable Object)


GetPrivateData Method (DatabaseTable Object)

The GetPrivateData method is used to retrieve the current private data for a given table. The private data will be returned as the type specified in the VariantType parameter. The format of the private data is specific to each database driver.

For example, if the report has been designed by using the crystal active data driver, see Active Data. GetPrivateData can be used to obtain the active data object assigned to the report by using SetPrivateData Method (DatabaseTable Object).

Syntax

object.GetPrivateData VariantType

Parameters

VariantType

A constant value indicating the type of data being retrieved. Use a Visual Basic VarType constant value. For example, vbDataObject will return an Active Data Object such as a DAO Recordset.

Returns

Variant.


SetLogOnInfo Method (DatabaseTable Object)

Sample Code - SetLogOnInfo Method

The SetLogOnInfo method logs on to the data source so table data can be accessed.

Syntax

object.SetLogOnInfo DllName, ServerName, DatabaseName, UserID, Password

Parameters

DllName | Specifies the DLL used to access the database by the Crystal Report Engine (that is, PDSODBC.DLL).
ServerName | Specifies the name of the server or ODBC data source where the database is located (that is, CRSS).
DatabaseName (Optional) | Specifies the name of the database.
UserID (Optional) | Specifies a valid user name for logging on to the data source.
Password (Optional) | Specifies a valid password for logging on to the data source.


SetPrivateData Method (DatabaseTable Object)

The SetPrivateData method is used to provide information about a data source to the database driver associated with this DatabaseTable object. For instance, if a report has been designed by using the crystal active data driver, this method can be used to provide an active data source for the report, such as a DAO, ADO, or RDO Recordset or a CDO Rowset. In this case, the object passed to the second parameter of this method replaces, at runtime, the field definition file used to create the report. For complete information, see Active Data.

Syntax

object.SetPrivateData DataTag, Data

Parameters

DataTag | A value indicating the type of data being passed to the DatabaseTable object in the Data parameter. Currently, the only possible value is 3. This value must be used for all Active data sources including DAO, ADO, RDO, CDO, and the Visual Basic data control.
Data | Variant data passed to the database driver. For example, with Active data, this must be a Recordset object if you are using DAO, ADO, or the Visual Basic data control. This must be a Rowset object if you are using CDO.


SetSessionInfo Method (DatabaseTable Object)

The SetSessionInfo method allows the user to log on to a secured Access session.

Syntax

object.SetSessionInfo SessionUserID As String, SessionPassword As String

Parameters

SessionUserID | Specifies the Access userID used to log on to an Access session.
SessionPassword | Specifies the session password for Access secured session.

Remarks

In Microsoft Access 95 and later, an Access database can have session security (also know as user-level security), database-level security, or both. If the Access database contains only session security, simply pass the session password to the SessionPassword parameter. If the Access database contains database-level security, use a linefeed character, Chr(10), followed by the database-level password. For example:

object.SetSessionInfo "userID", Chr(10) & "dbpassword"

If the Access database contains both session security and database-level security, use the session password followed by the linefeed character and the database password:

object.SetSessionInfo "userID", "sesspswd" & _

    Chr(10) & "dbpassword"

Alternately, database-level security can also be handled by assigning the database-level password to the Password parameter of the SetLogOnInfo Method (DatabaseTable Object), method.


TestConnectivity Method (DatabaseTable Object)

The TestConnectivity method tests to see if the database can be logged on to with the current information and if the database table can be accessed by the report.

Syntax

object.TestConnectivity

Returns
  • TRUE if the database session, logon, and location information are all correct.
  • FALSE if something is wrong.


DatabaseTables Collection

Sample Code - DatabaseTables Collection

The DatabaseTables Collection is a collection of DatabaseTable objects. A DatabaseTable object exists for every database object (that is, table, query, stored procedure, etc.) accessed by the report. Access a specific DatabaseTable Object, in the collection by using the Item property.

DatabaseTables Collection Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Count | Returns the number of database objects in the collection. | Read only
Item | Returns DatabaseTable Object. Item has an index parameter that can be either a string reference to the table, (that is, Item("Catgories")) or a numeric, 1-based index (that is, Item (1)). When a numeric index is used, the items in the collection are indexed in the order that they were added to the report. | Read only
Parent | Reference to the Parent object (Database Object). | Read only
Report | Reference to Report Object. | Read only

Remarks

Instead of using the Item property as shown, you can reference a table directly (for example, DatabaseTable("Categories") or DatabaseTable(1)).


EventInfo Object

EventInfo Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
ActivatePrint WindowEvent-Enabled | Returns/Sets a Boolean value indicating whether the ActivatePrintWindow Event (Window Object), or DeactivatePrintWindow Event (Window Object), events of the Window Object, are enabled. | Read/Write
ClosePrintWindow Event-Enabled | Returns/Sets a Boolean value indicating whether the ClosePrintWindow Event (Window Object), event of the Window Object, is enabled. | Read/Write
GroupEventEnabled | Returns Boolean value indicating whether the GroupTreeButtonClicked Event (Window Object), ShowGroup Event (Window Object), or DrillOnGroup Event (Window Object), events of the Window Object, are enabled. | Read only
Parent | Reference to the Parent object (Report Object). | Read only
PrintWindowButton Event-Enabled | Returns Boolean value indicating if events corresponding to preview window buttons for the Window Object, are enabled. | Read only
ReadingRecords EventEnabled | Returns Boolean value indicating if the ReadingRecords Event (Report Object), event of the Report Object, is enabled. | Read only
Report | Reference to Report Object. | Read only
StartStopEventEnabled | Returns Boolean value indicating if the Start Event (Report Object), and Stop Event (Report Object), events of the Report Object, are enabled. | Read only


ExportOptions Object

Sample Code - ExportOptions Object

The ExportOptions Object provides properties and methods for retrieving information and setting options for exporting your report (that is, export format, destination, etc.). An ExportOptions Object is obtained from the ExportOptions property of the Report Object.

ExportOptions Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
CharFieldDelimiter | Returns/Sets the character used to separate fields in character separated text formats. This character delimits every field in the file. | Read/Write
CharStringDelimiter | Returns/Sets the character used to separate strings in character separated text formats. This character delimits only string fields (numeric, date fields, etc., have no delimiter). | Read/Write
DestinationDLLName | Returns the name of the DLL used to export the report to a specific destination. | Read only
DestinationType | Returns/Sets CRExportDestinationType (see table below) indicating the destination type for the exported report (that is, disk, mail, etc.). | Read/Write
 | Constant | Value
 | crEDTDiskFile | 1
 | crEDTMailMAPI | 2
 | crEDTMailVIM | 3
 | crEDTMicrosoftExchange | 4
 | crEDTNoDestination | 0
Property | Description | Read/Write
DiskFileName | Returns/Sets the file name if the report is exported to a disk. | Read/Write
ExcelTabHasColumn Headings | Returns/Sets Boolean value indicating whether when exporting to Excel format, the spreadsheet will be displayed including column headings. By default this property is set to FALSE. | Read/Write
ExchangeDestination Type | Returns/Sets CRExchangeDestinationType (see table below) indicating the Exchange destination type for reports exported to Exchange folders. | Read/Write
 | Constant | Value
 | crExchangePostDocMessage | 1011
 | crExchangeFolderType | 0
Property | Description | Read/Write
ExchangeFolderPath | Returns/Sets the path of the Exchange folder for reports exported to Exchange (that is, "PersonalFolders@Inbox"). | Read/Write
ExchangePassword | Returns/Sets the password used to access the Exchange folder for reports exported to the 16-bit version of Exchange. | Read/Write
ExchangeProfile | Returns/Sets a user profile for accessing an Exchange folder for reports exported to Exchange. | Read/Write
FormatDLLName | Returns the file name of the DLL corresponding to the export format. | Read only
FormatType | Returns/Sets CRExportFormatType (see table below) indicating the format type for the exported report (that is, text, Excel, etc.). | Read/Write
 | Constant | Value
 | crEFTCharSeparatedValues | 7
 | crEFTCommaSeparatedValues | 5
 | crEFTCrystalReport | 1
 | crEFTDataInterchange | 2
 | crEFTExcel21 | 18
 | crEFTExcel30 | 19
 | crEFTExcel40 | 20
 | crEFTExcel50 | 21
 | crEFTExcel50Tabular | 22
 | crEFTExplorer32Extend | 25
 | crEFTHTML32Standard | 24
 | crEFTLotus123WK3 | 13
 | crEFTLotus123WK1 | 12
 | crEFTLotus123WKS | 11
 | crEFTNetScape20 | 26
 | crEFTNoFormat | 0
 | crEFTODBC | 23
 | crEFTPaginatedText | 10
 | crEFTQuattroPro50 | 17
 | crEFTRecordStyle | 3
 | crEFTRichText | 4
 | crEFTTabSeparatedText | 9
 | crEFTTabSeparatedValues | 6
 | crEFTText | 8
 | crEFTWordForDOS | 15
 | crEFTWordForWindows | 14
 | crEFTWordPerfect | 16
Property | Description | Read/Write
HTMLFileName | Returns/set the HTML file name for reports exported to HTML format. | Read/Write
MailBccList | Returns/Sets a Blind Carbon Copy (BCC) list for reports e-mailed to a VIM e-mail account. | Read/Write
MailCcList | Returns/Sets a Carbon Copy (CC) list for reports e-mailed. | Read/Write
MailMessage | Returns/Sets the e-mail message included with e-mailed reports. | Read/Write
MailSubject | Returns/Sets the e-mail subject heading for reports being e-mailed. | Read/Write
MailToList | Returns/Sets the To list for reports being e-mailed. | Read/Write
NumberOfLinesPer Page | Integer. Gets or sets the number of lines to appear per page option for reports exported to a paginated text format. | Read/Write
ODBCDataSource Name | Returns/Sets the ODBC data source for reports exported to ODBC. | Read/Write
ODBCDataSourcePassword | Returns/Sets the password used to access an ODBC data source for reports exported to ODBC. | Read/Write
ODBCDataSource UserID | Returns/Sets the user name used to access an ODBC data source for reports exported to ODBC. | Read/Write
ODBCExportTable Name | Returns/Sets the database table in the ODBC data source that the report file exported to ODBC will be appended to. You can also create a new table using this property. | Read/Write
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only
UseReportDateFormat | Returns/Sets whether the date format used in the report should also be used in the exported report. Can be used for Data Interchange Format (DIF), Record Style Format, and comma, tab, or character separated format. | Read/Write
UseReportNumber Format | Returns/Sets whether the number format used in the report should also be used in the exported report. Can be used for Data Interchange Format (DIF), Record Style Format, and comma, tab, or character separated format. | Read/Write


ExportOptions Object Methods

PromptForExportOptions Method (ExportOptions Object)

Reset Method (ExportOptions Object)


PromptForExportOptions Method (ExportOptions Object)

The PromptForExport Options method prompts the user for export information using default Crystal Report Engine dialog boxes.

Syntax

object.PromptForExportOptions


Reset Method (ExportOptions Object)

The Reset method clears all ExportOptions properties.

Syntax

object.Reset


FieldDefinitions Collection

The FieldDefinitons Collection is a collection of field definitions of all types. This collection is obtained from the DataFields property of the GraphObject Object. The collection of fields represents the fields used to plot the values on a chart. Access a specific FieldDefinition object in the collection using the Item property.

FieldDefinitions Collection Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Count | Returns the number of field definitions contained by this collection. | Read only
Item | Returns specific FieldDefnition objects in this collection. Item has an index parameter that is a numeric, 1-based index (that is, Item (1)). The items in the collection are indexed in the order that they are charted. | Read only
Parent | Reference to the Parent object (GraphObject Object). | Read only
Report | Reference to Report Object. | Read only

Remarks

Instead of using the Item property as shown, you can reference a field definition directly (for example, FieldDefinitions (1)).


FieldObject Object

Sample Code - FieldFormat Object

The FieldObject Object represents a field found in a report (that is,special field, database field, parameter field, etc.). This object provides properties for retrieving information for a field in your report. A FieldObject Object is obtained from the Item property of the ReportOptions Object (that is, ReportObjects.Item(Index)), where the index references a special field, database field, parameter field, summary field, or group name field (except BLOB field -- see BlobFieldObject Object).

Field Object Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Field | Returns the field definition object (depending on what the field object is, for example, DatabaseFieldDefinition Object, FormulaFieldDefinition Object, GroupNameFieldDefinition Object, ParameterFieldDefinition Object, SummaryFieldDefinition Object, and SpecialVarFieldDefinition Object). | Read only
Font | Returns Font Object, with information on what type of font is being used (for example, name). | Read only
Kind | Returns CRObjectKind object which specifies what "kind" of object (that is, box, cross-tab, field, etc.). | Read only
 | Constant | Value
 | crBlobFieldObject | 9
 | crBoxObject | 4
 | crCrossTabObject | 8
 | crFieldObject | 1
 | crGraphObject | 7
 | crLineObject | 3
 | crOleObject | 6
 | crSubreportObject | 5
 | crTextObject | 2
Property | Description | Read/Write
Parent | Reference to the Parent object (Section Object). | Read only
Report | Reference to Report Object. | Read only


FieldValue Object

The FieldValue Object is only available through the Window Object, event DrillOnDetail Event (Window Object), used in Visual Basic 5.0. When a user drills down on a Detail record value, all fields for that record are stored in an array of FieldValue objects that is returned in the FieldValues parameter of the DrillOnDetail event.

FieldValue Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Name | Returns the name of the field. | Read only
Parent | Reference to the Parent object (Window Object). | Read only
Report | Reference to Report Object. | Read only
Value | Returns the data contained in the field. | Read only


Font Object

The Font Object provides properties for retrieving information and setting options for the font used in a specified field (that is, Bold, line style, etc.). A Font Object is obtained from the Font property of the FieldObject Object. Options, such as font name, defined by this object are dependent upon the printer driver selected for the report.

Note: You must always use a prefix when referencing the Font Object. Visual Basic includes a VB Font Object that is always included when creating a project, so conflicts will always occur unless the object is properly referenced (for example, CRPEAuto.Font). For more information see Object Naming Conflicts.

Font Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Color | Returns/Sets a number representing the color of the font. The number represents an OLE color that can be set by using RGB (that is, RGB (255, 0, 0 for red) or by specifying CRColor (see table below). | Read/Write
 | Constant | Value
 | crAqua | 16776960
 | crBlack | 0
 | crBlue | 16711680
 | crFuchsia | 16711935
 | crGray | 8421504
 | crGreen | 32768
 | crLime | 65280
 | crMaroon | 128
 | crNoColor | -1
 | crOlive | 32896
 | crPurple | 8388736
 | crRed | 255
 | crSilver | 12632256
 | crTeal | 8421376
 | crWhite | 16777215
 | crYellow | 65536
Property | Description | Read/Write
Italic | Returns/Sets Boolean value indicating whether or not the font is italicized. | Read/Write
Name | Returns/Sets the name of the font. Available fonts for any report are dependent upon the printer driver selected for the report. | Read/Write
Parent | Reference to the Parent object (FieldObject Object). | Read only
Report | Reference to Report Object. | Read only
Size | Returns/Sets the point size of the font. | Read/Write
Strike Through | Returns/Sets Boolean value indicating whether or not the font is struck out. | Read/Write
Underline | Returns/Sets Boolean value indicating whether or not the font is underlined. | Read/Write
Weight | Returns/Sets the weight of the font. CRFontWeight (see table below) can be used for convenience. | Read/Write
 | Constant | Value
 | crFWBold | 700
 | crFWDontCare | 0
 | crFWExtraBold | 800
 | crFWExtraLight | 200
 | crFWHeavy | 900
 | crFWLight | 300
 | crFWMedium | 500
 | crFWNormal | 400
 | crFWSemiBold | 600
 | crFWThin | 100


FormulaFieldDefinition Object

Sample Code - FormulaFieldDefinition Object

The FormulaFieldDefinition Object provides properties and methods for retrieving information and setting options for any formula field found in a report.

FormulaFieldDefinition Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
FormulaField Name | Returns the formula field name as it appears in the Formula Field list on the Formula Tab of the Insert Fields dialog box (for example, NewExampleFormula). | Read only
Kind | Returns CRFieldKind (see table below), which specifies what "kind" of field (that is, database, summary, formula, etc.). | Read only
 | Constant | Value
 | crDatabaseField | 1
 | crFormulaField | 2
 | crGroupNameField | 5
 | crParameterField | 6
 | crSpecialVarField | 4
 | crSummaryField | 3
Property | Description | Read/Write
Name | Returns the name of the formula field as it would be displayed (referenced) in the report (that is, {@NewExampleFormula}). | Read only
NumberOfBytes | Returns the number of bytes required to store the field data in memory. | Read only
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only
Text | Returns/Sets the text of the formula. The formula text is changed immediately in the report. With that in mind, you should check the validity of the formula immediately after setting the Text property. Use Check Method (FormulaFieldDefinition Object), to check formulas. If you generate a report with an invalid formula, you may receive and exception error. | Read/Write
ValueType | Returns CRFieldValueType (see table below), which specifies the "type" of value found in the field. | Read only
 | Constant | Value
 | crBitmapField | 17
 | crBlobField | 15
 | crBooleanField | 9
 | crChartField | 21
 | crCurrencyField | 8
 | crDateField | 10
 | crDateTimeField | 16
 | crIconField | 18
 | crInt16sField | 3
 | crInt16uField | 4
 | crInt32sField | 5
 | crInt32uField | 6
 | crInt8sField | 1
 | crInt8uField | 2
 | crNumberField | 7
 | crOleField | 20
 | crPersistentMemoField | 14
 | crPictureField | 19
 | crStringField | 12
 | crTimeField | 11
 | crTransientMemoField | 13
 | crUnknownField | 22


FormulaFieldDefinition Methods

Check Method (FormulaFieldDefinition Object)


Check Method (FormulaFieldDefinition Object)

Sample Code - Check Method

The Check method checks formula for errors (that is, syntax errors).

Syntax

object.Check

Returns

Returns a Boolean value,

  • TRUE if formula is valid.
  • FALSE if formula contains errors.
Remarks

You can use LastErrorCode and LastErrorString properties from the Report Object, in order to obtain details when FALSE is returned.


FormulaFieldDefinitions Collection

Sample Code - FormulaFieldDefinitions Collection

The FormulaFieldDefinitions Collection is a collection of named formulas in the report. Access a specific FormulaFieldDefinition Object, in the collection by using the Item property.

FormualFieldDefinitions Collection Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Count | Returns the number of formula field definitions in the collection. | Read only
Item | Returns FormulaFieldDefinition Object. Item has an index parameter that can be either a string reference to the formula field or a numeric, 1-based index. When a numeric index is used, the items in the collection are indexed in the order that they were added to the report. | Read only
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only

Remarks

Instead of using the Item property as shown, you can reference a formula field directly (for example, FormulaFieldDefinitions("ExampleFormula")).


GlobalOptions Object

The GlobalOptions Object provides properties for retrieving information or setting options for an application object. A GlobalOptions Object is obtained from the Options property of the Application Object.

GlobalOptions Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
MorePrintEngine ErrorMessages | Sets Boolean value indicating more error messages at the application level. Use this object to turn off more error messages if they are switched on by default. It will not affect more print error messages at the report level. | Write only
Parent | Reference to the Parent object (Application Object). | Read only


GraphObject Object

Sample Code - GraphObject Object

The GraphObject Object represents a graph/chart found in a report. This object provides properties for retrieving information and setting options for a chart in your report (that is, graph data type -- group, detail or graph display type -- bar, pie, etc.).

GraphObject Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, this object is associated with. | Read only
ColumnGroup Number | Returns/Sets the group number that the column of the graph gets its data from (that is, in a stacked bar graph, the "column" is the bar of the graph, so there will be one bar for each group). | Read/Write
ConditionField | Returns/Sets the Detail field to be graphed on. This property applies to only detail graphs; using this property with a cross-tab or group graph will result in an error. | Read/Write
CrossTabObject | Returns CrossTabObject Object, with information regarding the cross-tab object used to graph on. This property applies only to cross-tab graphs; using this property with a detail or group graph will result in an error. | Read only
DataFields | Returns the FieldDefinitions object that represents the data fields of the graph (that is, numeric fields for graph data). Specifies a collection of graph data fields. This property applies only to detail graphs; using this property with a cross-tab or group graph will result in an error. | Read only
DataType | Returns CRGraphDataType (see table below) which specifies the type of data used in the graph. | Read only
 | Constant | Value
 | crCrossTabGraph | 2
 | crDetailGraph | 1
 | crGroupGraph | 0
Property | Description | Read/Write
Direction | Returns/Sets CRGraphDirection (see table below) indicating if the graph groups on only the rows of a cross-tab, only the columns, or a combination of both (that is, for stacked bar graph). This property applies to only cross-tab graphs. | Read/Write
 | Constant | Value
 | crGDColumnsOnly | 1
 | crGDMixedColumnRow | 3
 | crGDMixedRowColumn | 2
 | crGDRowsOnly | 0
 | crGDUnknownDirection | 20
Property | Description | Read/Write
DisplayType | Returns/Sets CRGraphDisplayType (see table below) indicating which graph representation type used for the graph (that is, SideBySideGraph, PieGraph, etc.). | Read/Write
 | Constant | Value
 | crAreaGraph | 120
 | crFaked3DPercentBarGraph | 6
 | crFaked3DSideBySideBarGraph | 4
 | crFaked3DStackedBarGraph | 5
 | crLineGraph | 80
 | crMultiPieGraph | 42
 | crPercentBarGraph | 3
 | crPieGraph | 40
 | crProportionalMultiPieGraph | 43
 | crSideBySideGraph | 0
 | crStackedBarGraph | 2
 | crThreedBarGraph | 160
 | crUnkownTypeGraph | 1000
 | crUserDefinedGraph | 500
Property | Description | Read/Write
FontFaceName | Returns/Sets the font for the title, subtitle, and footnote text included with the graph. Fonts available for any report are dependent upon the printer driver selected for the report. | Read/Write
FootNote | Returns/Sets the footnote text that appears at the bottom of the graph. | Read/Write
GroupsTitle | Returns/Sets the title of the groups that are being graphed. | Read/Write
Kind | Returns CRObjectKind object (see table below), which specifies what "kind" of object (that is, box, cross-tab, field, etc.). | Read only
 | Constant | Value
 | crBlobFieldObject | 9
 | crBoxObject | 4
 | crCrossTabObject | 8
 | crFieldObject | 1
 | crGraphObject | 7
 | crLineObject | 3
 | crOleObject | 6
 | crSubreportObject | 5
 | crTextObject | 2
Property | Description | Read/Write
MaxValue | Returns/Sets the maximum value that will appear in the graph. Any graph values above this value are not graphed. | Read/Write
MinValue | Returns/Sets the minimum value that will appear in the graph. Any graph values below this value are not graphed. | Read/Write
Parent | Reference to the Parent object (Section Object). | Read only
Report | Reference to Report Object. | Read only
RowGroup Number | Returns/Sets the group number of the group that supplies the data for the graphs rows. For example, in a stacked bar graph, the row would be the stacked data. For graphs with no rows, this value is -1. (This property does not apply to a detail graph.) | Read/Write
SeriesTitle | Returns/Sets the title of the series which is being graphed. | Read/Write
ShowDataValue Enabled | Returns/Sets Boolean value indicating whether or not to display the numeric value associated with each riser on the graph. If set to TRUE (1), a value appears in the graph for each riser. | Read/Write
ShowGridLine Enabled | Returns/Sets Boolean value indicating whether or not to display grid lines on the graph. | Read/Write
ShowLegend Enabled | Returns/Sets Boolean value indicating whether or not to display the graph legend. | Read/Write
ShowVerticalBar Enabled | Returns/Sets Boolean value indicating whether to display the bars in a bar graph vertically or horizontally. | Read/Write
SubTitle | Returns/Sets the subtitle text that will appear directly under the main title. | Read/Write
SummarizedField | Returns/Sets SummaryFieldDefinition Object, used to supply the data for a group graph. (This property does not apply to a detail graph.) | Read/Write
Title | Returns/Sets the main title text that will appear above the graph. | Read/Write
XAxisTitle | Returns/Sets the text that will appear for the X axis. Not valid for Pie graphs. | Read/Write
YAxisTitle | Returns/Sets the text that will appear for the Y axis. Not valid for Pie graphs. | Read/Write
ZAxisTitle | Returns/Sets the text that will appear for the Z axis. This value is only valid for 3D graphs. | Read/Write


GroupAreaOptions Object

The GroupAreaOptions Object provides properties for retrieving information and setting options for a group area found in a report (that is, keep group together, sort direction, etc.). A GroupAreaOptions Object is obtained from the GroupOptions property of the Area Object.

GraphAreaOptions Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Condition | Returns/Sets CRGroupCondition (see table below) indicating when grouping should occur for Boolean or Date groups (that is, for Boolean groups, group on change to TRUE; for date groups, group dates weekly, etc.). | Read/Write
 | Constant | Value
 | crGCAnnually | 7
 | crGCAnyValue | 14
 | crGCBiweekly | 2
 | crGCDaily | 0
 | crGCEveryNo | 11
 | crGCEveryYes | 10
 | crGCMonthly | 4
 | crGCNextIsNo | 13
 | crGCNextIsYes | 12
 | crGCQuarterly | 5
 | crGCSemiAnnually | 6
 | crGCSemiMonthly | 3
 | crGCToNo | 9
 | crGCToYes | 8
 | crGCWeekly | 1
Property | Description | Read/Write
ConditionField | Returns/Sets DatabaseFieldDefinition Object, specifying the field that grouping occurs on. | Read/Write
DiscardOther Groups | Returns/Sets Boolean value indicating if "other" groups in a group sort are discarded (that is, those not included in a Top/Bottom N group sort when sorting groups by their summary field). | Read/Write
KeepGroupTogether | Returns/Sets Boolean value to keep group together (that is, across page breaks). | Read/Write
NumberOfTopOr BottomGroups | Returns/Sets the number of groups for a TopN group sort. | Read/Write
Parent | Reference to the Parent object (Area Object). | Read only
RepeatGroup Header | Returns/Sets Boolean value indicating if group headers should be repeated when group is split across pages. | Read/Write
Report | Reference to Report Object. | Read only
SortDirection | Returns/Sets CRSortDirection (see table below) indicating the sort direction of the group name field, as opposed to the group summary field. | Read/Write
 | Constant | Value
 | crAscendingOrder | 1
 | crDescendingOrder | 0
 | crOriginalOrder | 2
 | crSpecifiedOrder (Read only -- this value cannot be set.) | 3
Property | Description | Read/Write
TopOrBottomN Groups | Returns/Sets the value of CRTopBottomNGroupSortOrder (see table below) indicating which section of groups will be shown (that is, TopN groups, BottomN groups, all groups, etc.). | Read/Write
 | Constant | Value
 | crAllGroupsSorted. | 1
 | crAllGroupsUnsorted | 0
 | crBottomNGroups | 3
 | crTopNGroups | 2


GroupNameFieldDefinition Object

The GroupNameFieldDefinition Object provides properties and methods for retrieving information on a group name field found in a report (that is, number of group, value type, etc.). A GroupNameFieldDefinition Object is obtained from the Field property of the FieldObject Object, when the specified field is a group name field.

GroupNameFieldDefinition Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
GroupNumber | Returns the group number of the specified group. | Read only
Kind | Returns CRFieldKind (see table below), which specifies what "kind" of field (that is, database, summary, formula, etc.). | Read only
 | Constant | Value
 | crDatabaseField | 1
 | crFormulaField | 2
 | crGroupNameField | 5
 | crParameterField | 6
 | crSpecialVarField | 4
 | crSummaryField | 3
Name | Returns the name of the group name field. | Read only
NumberOfBytes | Returns the number of bytes required to store the field data in memory. | Read only
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only
ValueType | Returns CRFieldValueType (see table below), which specifies the "type" of value found in the field. | Read only
 | Constant | Value
 | crBitmapField | 17
 | crBlobField | 15
 | crBooleanField | 9
 | crChartField | 21
 | crCurrencyField | 8
 | crDateField | 10
 | crDateTimeField | 16
 | crIconField | 18
 | crInt16sField | 3
 | crInt16uField | 4
 | crInt32sField | 5
 | crInt32uField | 6
 | crInt8sField | 1
 | crInt8uField | 2


LineObject Object

The LineObject Object represents a line drawn on a report. This object provides properties for getting information for lines on a report.

LineObject Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Kind | Returns CRObjectKind (see table below), which specifies what "kind" of object (i.e., box, cross-tab, field, etc.). | Read only
 | Constant | Value
 | crBlobFieldObject | 9
 | crBoxObject | 4
 | crCrossTabObject | 8
 | crFieldObject | 1
 | crGraphObject | 7
 | crLineObject | 3
 | crOleObject | 6
 | crSubreportObject | 5
 | crTextObject | 2
Property | Description | Read/Write
Parent | Reference to the Parent object (Section Object). | Read only
Report | Reference to Report Object. | Read only


OLEObject Object

The OLEObject Object represents an OLE object in a report. This object provides properties for getting information for OLE objects in a report.

OLEObject Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Kind | Returns CRObjectKind (see table below), which specifies what "kind" of object (i.e., box, cross-tab, field, etc.). | Read only
 | Constant | Value
 | crBlobFieldObject | 9
 | crBoxObject | 4
 | crCrossTabObject | 8
 | crFieldObject | 1
 | crGraphObject | 7
 | crLineObject | 3
 | crOleObject | 6
 | crSubreportObject | 5
 | crTextObject | 2
Property | Description | Read/Write
Parent | Reference to the Parent object (Section Object). | Read only
Report | Reference to Report Object. | Read only


Page Object

The Page Object is part of the Page Engine. Use the Page Engine when designing web sites using Active Server Pages, the Crystal Report Engine Automation Server, and the Crystal Design-Time ActiveX Control. Unless you are experienced with the Crystal Report Engine Object Model, you should allow the Crystal Design-Time ActiveX Control to generate VBScript code, in your Active Server Pages, to control the Page Engine objects.

The Page Engine generates pages of a report on the web server and sends the pages to client web browsers as they are requested. For example, when a user first requests a report, only the first page is sent to the web browser. If the user pages forward or backward in the report, or requests a specific page, only that page is sent. This limits the resources required by the web server and reduces download time for the client browser. A Page Object is a single generated page that is sent to the browser.

Page Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
IsLastPage | Returns Boolean value indicating whether the page generated is the last page of the report. | Read only
PageNumber | Returns the page number of the page generated. | Read only
Parent | Reference to the Parent object (PageGenerator Object). | Read only
Report | Reference to Report Object. | Read only


Page Object Methods

RenderEPF Method (Page Object)

RenderHTML Method (Page Object)


RenderEPF Method (Page Object)

The RenderEPF method returns a variant that contains EPF code for the report page.

Syntax

variantdata = object.RenderEPF (ResultType as CRRenderResultType)

Parameters

ResultType | Returns CRRenderResultType (see table below) indicating whether the page will be rendered using strings or arrays.
 | Constant | Value
 | crBSTRType | 8
 | crUISafeArrayType | 8209


RenderHTML Method (Page Object)

The RenderHTML method returns a variant that contains HTML code for the report page.

Syntax
variantdata = object.RenderHTML (IncludeDrillDownLinks as Boolean,
PageStyle as CRHTMLPageStyle, ToolbarStyle as CRHTMLToolbarStyle,
BaseURL as string, ResultType as CRRenderResultType)
Parameters

IncludeDrill DownLinks | Indicates whether or not the HTML page will include hyperlinks for drilling down on summary data.
PageStyle | Specifies CRHTMLPageStyle (see table below) indicating the style of the HTML page to be rendered.
 | Constant | Value
 | crFramePageStyle | 2
 | crPlainPageStyle | 0
 | crToolbarPageStyle | 1
ToolbarStyle | Specifies CRHTMLToolbarStyle (see table below) indicating the style of the toolbar to be used.
 | Constant | Value
 | crToolbarRefreshButton | 1
 | crToolbarSearchBox | 2
BaseURL | The URL used to access the report when it is first generated.
ResultType | Returns CRRenderResultType (see table below) indicating whether the page will be rendered using strings or arrays.
 | Constant | Value
 | crBSTRType | 8
 | crUISafeArrayType | 8209


PageEngine Object

Use the PageEngine object when designing web sites using Active Server Pages, the Crystal Report Engine Automation Server, and the Crystal Design-Time ActiveX Control. Unless you are experienced with the Crystal Report Engine Object Model, you should allow the Crystal Design-Time ActiveX Control to generate VBScript code, in your Active Server Pages, to control the Page Engine objects.

The Page Engine generates pages of a report on the web server and sends the pages to client web browsers as they are requested. For example, when a user first requests a report, only the first page is sent to the web browser. If the user pages forward or backward in the report, or requests a specific page, only that page is sent. This limits the resources required by the web server and reduces download time for the client browser.

PageEngine Object Properties

Property | Description | Read/Write
ImageOptions | Returns/Sets CRImageType (see table below) indicating the image type for EPF format. | Read/Write
 | Constant | Value
 | crDIBImageType | 1
 | crJPEGImageType | 2


PageEngine Object Methods

CreatePageGenerator Method (PageEngine Object)

RenderTotallerETF Method (PageEngine Object)

RenderTotallerHTML Method (PageEngine Object)


CreatePageGenerator Method (PageEngine Object)

The CreatePageGenerator method returns a PageGenerator Object, allowing you to get pages from the view of the report, specified by the GroupPath parameter.

Syntax

PgGenObject = object.CreatePageGenerator (GroupPath)

Parameters

GroupPath

Specifies an integer array that represents the group path (separated by "/"). An empty array would represent the entire report, an array (0, 1) would represent a drill down on the second group member within the first group member (i.e., 0 = first group in Group #1 and 1 = second group in Group #2).

Note: Another optional parameter, DrillDownLevel, will appear in the Object Browser for the CreatePageGenerator Method. This parameter has not been implemented; the value will be ignored.


RenderTotallerETF Method (PageEngine Object)

The RenderTotallerETF method returns a variant that contains ETF code for the Group Tree.

Syntax
variantData = object.RenderTotallerETF (RootGroupPath,
StartingChildNumber, PastRootLevels, MaxNodeCount, ResultType)
Parameters

MaxNodeCount | The maximum number of nodes for the Group Tree. |
PastRootLevels | An array of past root levels. |
ResultType | Returns CRRenderResultType (see table below) indicating whether the page will be rendered by using strings or arrays. |
 | Constant | Value
 | crBSTRType | 8
 | crUISafeArrayType | 8209
RootGroupPath | Specifies an integer array that represents the root group path (separated by "/"). An empty array would represent the entire report, an array (0, 1) would represent a drill-down on the second group member within the first group member (that is, 0 = first group in Group #1 and 1 = second group in Group #2). |
StartingChildNumber | The child level to display the report grouping at. |


RenderTotallerHTML Method (PageEngine Object)

The RenderTotallerHTML method returns a variant that contains HTML code for the Group Tree.

Syntax
variantData = object.RenderTotallerHTML (RootGroupPath,
StartingChildNumber, PastRootLevels, MaxNodeCount, OpenGroupPath,
IncludeDrillDownLinks, BaseURL, ResultType)
Parameters

BaseURL | The URL address of the report when it is first generated by the web server.
IncludeDrill DownLinks | Indicates whether or not drill-down hyperlinks are generated for summary values in the report.
MaxNodeCount | The maximum number of nodes to display in the Group Tree.
OpenGroupPath | An array of groups to be opened in the report.
PastRootLevels | A value indicating the number of past root levels.
ResultType | Returns CRRenderResultType (see table below) indicating whether the page will be rendered by using strings or arrays.
 | Constant | Value
 | crBSTRType | 8
 | crUISafeArrayType | 8209
RootGroupPath | Specifies an integer array that represents the root group path (separated by "/"). An empty array would represent the entire report, an array (0, 1) would represent a drill-down on the second group member within the first group member (that is, 0 = first group in Group #1 and 1 = second group in Group #2).
StartingChild Number | Long


PageGenerator Object

The PageGenerator Object is part of the Page Engine. Use the Page Engine when designing web sites using Active Server Pages, the Crystal Report Engine Automation Server, and the Crystal Design-Time ActiveX Control. Unless you are experienced with the Crystal Report Engine Object Model, you should allow the Crystal Design-Time ActiveX Control to generate VBScript code, in your Active Server Pages, to control the Page Engine objects.

The Page Engine generates pages of a report on the web server and sends the pages to client web browsers as they are requested. For example, when a user first requests a report, only the first page is sent to the web browser. If the user pages forward or backward in the report, or requests a specific page, only that page is sent. This limits the resources required by the web server and reduces download time for the client browser. A PageGenerator object generates Page Object, as they are requested and allows options for manipulating the report as a whole.

PageGenerator Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
GroupPath | Returns the GroupPath parameter set by CreatePageGenerator Method (PageEngine Object). | Read only
Pages | Returns Pages Collection, which is a collection of pages in the report. | Read only
Parent | Reference to the Parent object (PageEngine Object). | Read only
Report | Reference to Report Object. | Read only


PageGenerator Object Methods

DrillOnGraph Method (PageGenerator Object)

GetPageNumberForGroup Method (PageGenerator Object)

SearchForText Method (PageGenerator Object)


DrillOnGraph Method (PageGenerator Object)

The DrillOnGraph method creates a new PageGenerator Object, that results from drilling down on the specified point in a graph on the given page.

Syntax

pgGenObject = object.DrillOnGraph (PageNumber, XOffset, YOffset)

Parameters
PageNumber | Specifies the page number.
XOffset | Specifies the X coordinate on page in twips where the drill-down occurred.
YOffset | Specifies the Y coordinate on page in twips where the drill-down occurred.


GetPageNumberForGroup Method (PageGenerator Object)

The GetPageNumberForGroup method returns the page number on which the given group starts.

Syntax

numbervar = object.GetPageNumberForGroup (GroupPath)

Parameters

GroupPath

Specifies an integer array that represents the group path (separated by "/"). An empty array would represent the entire report, an array (0, 1) would represent a drill-down on the second group member within the first group member (i.e., 0 = first group in Group #1 and 1 = second group in Group #2).


SearchForText Method (PageGenerator Object)

The SearchForText method searches for the given text, starting on the given page. If the text is found, the PageNumber is set to the number of the page on which it was found. Returns a Boolean value indicating if text was found.

Syntax

Boolean = object.SearchForText (Text, Direction, PageNumber)

Parameters

Direction | Specifies CRSearchDirection (see table below) indicating the direction to sort in.
 | Constant | Value
 | crAscendingOrder | 1
 | crDescendingOrder | 0
 | crOriginalOrder | 2
PageNumber | Specifies the page to start searching in and returns the page number of the first occurrence of the sought-after text. |
Text | Specifies the text string being searched for. |


Pages Collection

The Pages Collection is part of the Page Engine. Use the Page Engine when designing web sites using Active Server Pages, the Crystal Report Engine Automation Server, and the Crystal Design-Time ActiveX Control. Unless you are experienced with the Crystal Report Engine Object Model, you should allow the Crystal Design-Time ActiveX Control to generate VBScript code, in your Active Server Pages, to control the Page Engine objects.

The Page Engine generates pages of a report on the web server and sends the pages to client web browsers as they are requested. For example, when a user first requests a report, only the first page is sent to the web browser. If the user pages forward or backward in the report, or requests a specific page, only that page is sent. This limits the resources required by the web server and reduces download time for the client browser.

The Pages Collection is a collection of Page Object. Access a specific Page Object in the collection using the Item property.

Pages Collection Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Count | Returns the number of page objects in the collection. | Read only
Item | Returns Page Object. Item has an index parameter that is a numeric, 1-based index (that is, Item (1)). | Read only
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only

Remarks

Instead of using the Item property as shown, you can reference a page directly (Pages (1), for example).


PageSetup Object

The PageSetup Object provides properties for retrieving information and setting options for page setup in a report (that is, paper size, margins, etc.) for the current printer. A PageSetup Object is obtained from the PageSetup property of the Report Object. If the current printer is changed with the ReportObject SelectPrinter method, then the values in PageSetup Object properties may change.

PageSetup Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
BottomMargin | Returns/Sets value specifying the bottom margin, in twips. See Remarks below. | Read/Write
LeftMargin | Returns/Sets value specifying the left margin, in twips. See Remarks below. | Read/Write
PaperOrientation | Returns/Sets CRPaperOrientation, using one of the following constants, indicating the paper orientation. See Remarks below. | Read/Write
 | Constant | Value
 | crDefaultPaperOrientation (Read Only) | 0
 | crLandscape | 2
 | crPortrait | 1
PaperSize | Returns/Sets CRPaperSize, using one of the following constants, indicating the paper size. Check your printer documentation for a list of paper sizes available for use with your printer. If you choose an unavailable paper size, the default (letter) size will be used. See Remarks below. | Read/Write
 | Constant | Value
 | crDefaultPaperSize (Read Only) | 0
 | crPaper10x14 | 16
 | crPaper11x17 | 17
 | crPaperA3 | 8
 | crPaperA4 | 9
 | crPaperA4Small | 10
 | crPaperA5 | 11
 | crPaperB4 | 12
 | crPaperB5 | 13
 | crPaperCsheet | 24
 | crPaperDsheet | 25
 | crPaperEnvelope10 | 20
 | crPaperEnvelope11 | 21
 | crPaperEnvelope12 | 22
 | crPaperEnvelope14 | 23
 | crPaperEnvelope9 | 19
 | crPaperEnvelopeB4 | 33
 | crPaperEnvelopeB5 | 34
 | crPaperEnvelopeB6 | 35
 | crPaperEnvelopeC3 | 28
 | crPaperEnvelopeC4 | 29
 | crPaperEnvelopeC5 | 30
 | crPaperEnvelopeC6 | 31
 | crPaperEnvelopeC65 | 32
 | crPaperEnvelopeDL | 27
 | crPaperEnvelopeItaly | 36
 | crPaperEnvelopeMonarch | 37
 | crPaperEnvelopePersonal | 38
 | crPaperEsheet | 26
 | crPaperExecutive | 7
 | crPaperFanfoldLegalGerman | 41
 | crPaperFanfoldStdGerman | 40
 | crPaperFanfoldUS | 39
 | crPaperFolio | 14
 | crPaperLedger | 4
 | crPaperLegal | 5
 | crPaperLetter | 1
 | crPaperLetterSmall | 2
 | crPaperNote | 18
 | crPaperQuarto | 15
 | crPaperStatement | 6
 | crPaperTabloid | 3
Property | Description | Read/Write
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only
RightMargin | Returns/Sets value specifying the right margin, in twips. See Remarks below. | Read/Write
TopMargin | Returns/Sets value specifying the top margin, in twips. See Remarks below. | Read/Write

Remarks
  • PageSetup properties are retrieved and set for the current printer. If the current printer is changed using ReportObject method SelectPrinter, then the properties of PageSetup Object, for example, PaperOrientation, can change.
  • Properties BottomMargin, LeftMargin, RightMargin, and TopMargin values are in twips. A twip is 1/1440 of an inch; there are 20 twips in a point. To set .5" margins, for example, you would enter the value 720.
  • Properties BottomMargin, LeftMargin, RightMargin, and TopMargin are set to -1 by default. Unless otherwise specified, the default margins set in the report are used.
  • Properties PaperOrientation and PaperSize default constants (crDefaultPaperOrientation and crDefaultPaperSize) are Read Only. The other enums listed below each property can be passed when setting a value.


ParameterFieldDefinition Object

The ParameterFieldDefinition Object represents a parameter field in the report. This object provides properties and methods for retrieving information and setting options for a parameter field in your report (that is, current value, default value, etc.). A ParameterFieldDefinition Object is obtained from the Field property of the Area Object when the specified field is a parameter field.

ParameterFieldDefinition Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
CurrentValue | Returns the value entered by the user or when set using SetCurrentValue. If the user clicked Cancel or no value is set, a null is returned. | Read only
CurrentValueSet | Boolean value that will equal TRUE (1) if the user enters a value at the prompt or a value has been set using SetCurrentValue and FALSE (0) if the user clicks Cancel or no value has been set. | Read only
DefaultValue | Returns the default value assigned to the parameter field if one was set. If DefaultValueSet is FALSE, a null is returned. | Read only
DefaultValueSet | Returns Boolean value indicating whether or not a default value was set for the parameter field when the parameter field was created or modified in Crystal Reports. The value can be either TRUE (1) if the field was given a default value or FALSE (0) if it was not. | Read only
Kind | Returns CRFieldKind (see table below) which specifies what "kind" of field (database, summary, formula, etc.). | Read only
 | Constant | Value
 | crDatabaseField | 1
 | crFormulaField | 2
 | crGroupNameField | 5
 | crParameterField | 6
 | crSpecialVarField | 4
 | crrSQLExpressionField | 1
 | crSummaryField | 3
Name | Returns the name of the parameter field as it appears in the Parameter Field list on the Parameter Tab of the Insert Fields dialog box (for example, NewExampleParameter). | Read only
NeedsCurrentValue | Returns Boolean value indicating if the parameter needs a value entered (no current value is set). TRUE if no current value is set; FALSE if current value is set. | Read only
NumberOfBytes | Returns the number of bytes required to store the field data in memory. | Read only
ParameterField Name | Returns the name of the parameter field as it is displayed (referenced) in the report (that is, {?ExampleParameter}). | Read only
Parent | Reference to the Parent object (Report Object). | Read only
Prompt | Returns/Sets the prompting text, if any, that appears when the user runs the report for the first time or refreshes the data. This will be either the prompt assigned by the user when the parameter field was inserted into the report or the prompt that was set from code. | Read/Write
Report | Reference to Report Object. | Read only
ReportName | Returns the subreport name if the parameter is part of a subreport; otherwise, a null is returned. | Read only
ValueType | Returns CRFieldValueType (see table below), which specifies the "type" of value found in the field. | Read only
 | Constant | Value
 | crBitmapField | 17
 | crBlobField | 15
 | crBooleanField | 9
 | crChartField | 21
 | crCurrencyField | 8
 | crDateField | 10
 | crDateTimeField | 16
 | crIconField | 18
 | crInt16sField | 3
 | crInt16uField | 4
 | crInt32sField | 5
 | crInt32uField | 6
 | crInt8sField | 1
 | crInt8uField | 2
 | crNumberField | 7
 | crOleField | 20
 | crPersistentMemoField | 14
 | crPictureField | 19
 | crStringField | 12
 | crTimeField | 11
 | crTransientMemoField | 13
 | crUnknownField | 22


ParameterFieldDefinition Object Methods

SetCurrentValue Method (ParameterFieldDefinition Object)

SetDefaultValue Method (ParameterFieldDefinition Object)


SetCurrentValue Method (ParameterFieldDefinition Object)

The SetCurrentValue method sets the current value of the parameter. This is the value that will be used for the parameter in the report. If the current value is set, no prompt will appear for the parameter when the report is run.

Syntax

object.SetCurrentValue CurrentValue, ValueType

Parameters

CurrentValue | Specifies the value that you want to set the parameter field current value to. Can be number, currency, date, string, or Boolean.
ValueType (Optional) | Specifies CRFieldValueType (see table below) indicating the type of the current value (that is, number, currency, etc.). You may either change the parameter field type using this parameter or keep the current type (as specified in the report) by omitting this parameter.
 | Constant | Value
 | crBitmapField | 17
 | crBlobField | 15
 | crBooleanField | 9
 | crChartField | 21
 | crCurrencyField | 8
 | crDateField | 10
 | crDateTimeField | 16
 | crIconField | 18
 | crInt16sField | 3
 | crInt16uField | 4
 | crInt32sField | 5
 | crInt32uField | 6
 | crInt8sField | 1
 | crInt8uField | 2
 | crNumberField | 7
 | crOleField | 20
 | crPersistentMemoField | 14
 | crPictureField | 19
 | crStringField | 12
 | crTimeField | 11
 | crTransientMemoField | 13
 | crUnknownField | 22


SetDefaultValue Method (ParameterFieldDefinition Object)

The SetDefaultValue method sets the default value for the parameter. This is the value that will be used as the default shown when prompting for a value.

Syntax

object.SetDefaultValue DefaultValue, ValueType

Parameters

DefaultValue | Specifies the value that you want to set the parameter field default value to. Can be number, currency, date, string, or Boolean.
ValueType (Optional) | Specifies CRFieldValueType (see table below) indicating the type of the default value (i.e., number, currency, etc.). You may either change the parameter field type using this parameter or keep the current type (as specified in the report) by omitting this parameter.
 | Constant | Value
 | crBitmapField | 17
 | crBlobField | 15
 | crBooleanField | 9
 | crChartField | 21
 | crCurrencyField | 8
 | crDateField | 10
 | crDateTimeField | 16
 | crIconField | 18
 | crInt16sField | 3
 | crInt16uField | 4
 | crInt32sField | 5
 | crInt32uField | 6
 | crInt8sField | 1
 | crInt8uField | 2
 | crNumberField | 7
 | crOleField | 20
 | crPersistentMemoField | 14
 | crPictureField | 19
 | crStringField | 12
 | crTimeField | 11
 | crTransientMemoField | 13
 | crUnknownField | 22


ParameterFieldDefinitions Collection

The ParameterFieldDefinitions Collection is a collection of parameter fields in the report. If the report contains any subreports, parameter fields in the subreports will also be included in the collection. Access a specific ParameterFieldDefinition Object, in the collection by using the Item property.

ParameterFieldDefinitions Collection Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Count | Returns the number of parameter fields in the collection. | Read only
Item | Returns ParameterFieldDefinition Object, in a collection. This property has two parameters: Index and ReportName (optional). The index can be numeric (1-based): for example, Item(1). When a numeric index is used, the items in the collection are indexed in the order that they were added to the report followed by the parameter fields from any subreport, in the same order. The second parameter is not necessary if a numeric index is used. The index can also be a string, representing the parameter name. If the report name is not included, the parameter field is assumed to be in the primary report. If the parameter field exists in a subreport, you must also pass the subreport name as the second parameter for Item. | Read only
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only

Remarks

Instead of using the Item property as shown, you can reference a parameter field directly (for example, ParameterFieldDefinitions(1)).

PrinterInfo Object

The PrinterInfo Object provides properties for retrieving information and setting options for the specified printer used to print a report (that is, driver name, port name, etc.). A PrinterInfo Object is obtained from the PrinterInfo property of the Report Object.

PrinterInfo Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
DriverName | Returns the name of the printer driver for the printer that is selected in the report. If the default printer is used, no data is returned. | Read only
Parent | Reference to the Parent object (Report Object). | Read only
PortName | Returns the name of the printer port. If the default printer is used, no data is returned. | Read only
PrinterName | Returns the name of the printer. If the default printer is used, no data is returned. | Read only
Report | Reference to Report Object. | Read only


PrintingStatus Object

The PrintingStatus Object provides properties for retrieving information and setting options for the printing status of a report (that is, number of pages, latest page to be printed, etc.). A PrintingStatus Object is obtained from the PrintingStatus property of the Report Object.

PrintingStatus Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
LastestPage Number | Returns the number of the last page that is currently available. Once the printing is complete, this value is the number of the last page. You will receive an incorrect result if you try to obtain this value immediately after using a method such as ShowNextPage Method (View Object), that causes a change to the preview window. Call the Visual Basic function, DoEvents (see Visual Basic documentation for more information) before requesting the latest page number. | Read only
NumberOfPages | Returns the number of pages in the report. | Read only
Parent | Reference to the Parent object (Report Object). | Read only
Progress | Returns CRPrintingProgress (see table below) indicating the status of printing report (that is, cancelled, in progress, not started, etc.). Corresponds to PEJobInfo and PEGetJobStatus. | Read only
 | Constant | Value
 | crPrintingCancelled | 5
 | crPrintingCompleted | 3
 | crPrintingFailed | 4
 | crPrintingHalted | 6
 | crPrintingInProgress | 2
 | crPrintingNotStarted | 1
RecordsPrinted | Returns the number of records actually printed. You will receive an incorrect result if you try to obtain this value immediately after using a method such as ShowNextPage Method (View Object), that causes a change to the preview window. Call the Visual Basic function, DoEvents (see Visual Basic documentation for more information) before requesting the records printed. | Read only
RecordsRead | Returns the number of records actually processed. | Read only
RecordsSelected | Returns the number of records selected for inclusion in the report out of the total number of records read. | Read only
Report | Reference to Report Object. | Read only
StartPageNumber | Returns the number of the starting page of preview or printing. | Read only


PrintWindowOptions Object

The PrintWindowOptions Object provides properties for retrieving information and setting options for the print window (that is, available buttons, Group Tree, etc.). Many of the properties in this object must be set prior to enabling other events. For example, before enabling the CancelButtonClicked Event (Window Object), event from the Window Object, you must first set the HasCancelButton property from this object to TRUE. A PrintWindowOptions Object is obtained from the PrintWindowOptions property of the Report Object.

PrintWindowOptions Object Properties

Property | Description | Read/ Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
CanDrillDown | Returns/Sets Boolean value indicating whether you can drill down on previewed report. | Read/Write
HasCancelButton | Returns/Sets Boolean value indicating whether the preview window has a Cancel button. | Read/Write
HasCloseButton | Returns/Sets Boolean value indicating whether the preview window has a Close button. | Read/Write
HasExportButton | Returns/Sets Boolean value indicating whether the preview window has an Export button. | Read/Write
HasGroupTree | Returns/Sets Boolean value indicating whether the preview window includes the Group Tree. You must also set the HasGroupTree property to TRUE in the ReportOptions Object, to have the Group Tree show in the preview window. | Read/Write
HasNavigation Controls | Returns/Sets Boolean value indicating whether the preview window has navigation controls for moving through report pages. | Read/Write
HasPrintButton | Returns/Sets Boolean value indicating whether the preview window has a Print button. | Read/Write
HasPrintSetup Button | Returns/Sets Boolean value indicating whether the preview window has a Print Setup button. | Read/Write
HasProgress Controls | Returns/Sets Boolean value indicating whether the preview window has progress controls. | Read/Write
HasRefreshButton | Returns/Sets Boolean value indicating whether the preview window has a Refresh button. | Read/Write
HasSearchButton | Returns/Sets Boolean value indicating whether the preview window has a Search button. | Read/Write
HasZoomControl | Returns/Sets Boolean value indicating whether the preview window has zoom controls for changing the magnification of the report. | Read/Write
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only
TrackCursorInfo | Returns TrackCursorInfo Object. | Read only


Report Object

Sample Code - Creating a Report Object

A report corresponds to a print job in the Crystal Report Engine. When the report object is destroyed, or goes out of focus, it closes the print job. It holds on to Application Object. When a Report Object gets destroyed, it releases the application.

Access to the Report Object is dependent on the object variable you create. If the object variable goes out of scope, you will lose access to the Report Object and, therefore, the report. You may want to declare your Report Object variable as Global.

Report Object Properties

Properties Description Read/Write

Application

Returns a reference to the Application Object, that this object is associated with.

Read only

Areas

Returns Areas Collection, a collection of all the areas in the report which can be indexed by a number or by a string, such as "RH", "GF1". The areas are in the same order as on the Crystal Reports Design Tab (for example: RH, PH, GH1,...GHn, D, GFn,...GF1, RF, PF). The abbreviations for areas are case-sensitive.

Read only

Database

Returns the Database Object, which represents the database used in the report.

Read only

DialogParent
Window

Sets the parent window of report dialog boxes. If not set, the parent window is the preview window.

Write only

EventInfo

Returns EventInfo Object.

Read only

ExportOptions

Returns ExportOptions Object.

Read only

FormulaFields

Returns FormulaFieldDefinitions Collection, a collection of all the named FormulaFieldDefinitions defined in the Report.

Read only

GroupSelection
Formula

Returns/Sets the group selection formula.

Read/Write

GroupSortFields

Returns SortFields Collection, a collection of group sort fields.

Read only

HasSavedData

Returns Boolean value indicating whether report includes saved data.

Read only

LastErrorCode

Returns last error code for report-level errors.

Read only

LastErrorString

Returns last error string for report-level errors.

Read only

NumberOf
Group

Returns the number of groups in the report.

Read only

Options

Returns ReportOptions Object.

Read only

PageEngine

Returns PageEngine Object.

Read only

PageSetup

Returns PageSetup Object.

Read only

ParameterFields

Returns ParameterFieldDefinitions Collection, a collection of all the ParameterFieldDefinitions defined in the report. This property will return parameter field found in the main report as well as any subreports included in the report (that is, if the main report has 3 parameters and if a subreport included within the report has an additional 2 parameters, the number of parameter fields in the collection returned by Report.ParameterFields would be 5.

Read only

Parameter
Prompting
Enabled

Returns/Sets Boolean value indicating whether prompting dialog box for parameter field information is used.

  • If current values of all parameters are set, no prompting will occur for parameters, even if this is set to TRUE.
  • If current values of all parameters are not set, prompting will occur for parameters that need a current value if this is set to FALSE.

Read/Write

Parent

Reference to the Parent object (Application Object).

Read only

PrintDate

Returns/Sets the print date for the report. By default, the current date will be used.

Read/Write

PrinterInfo

Returns PrinterInfo Object.

Read only

PrintingStatus

Returns PrintingStatus Object.

Read only

PrintWindow
Options

Returns PrintWindowOptions Object.

Read only

ProgressDialog
Enabled

Sets Boolean value indicating whether or not to enable the progress dialog box when printing or exporting.

Write only

RecordSelection
Formula

Returns/Sets record selection formula.

Read/Write

RecordSort
Fields

Returns SortFields Collection, a collection of record sort fields.

Read only

ReportSummary
Info

Returns ReportSummaryInfo Object.

Read only

Sections

Returns Sections Collection, a collection of all the sections in the report.

Read only

SQLQuery
String

Returns/Sets the SQL query used in the report. Sample Code - SQLQueryString Property

Read/Write

SummaryFields

Returns SummaryFieldDefinitions Collection, for group and report summaries (cross-tab summaries not available when using this property).

Read only


Report Object Methods

AddGroup Method (Report Object)—CRE Object Model For the Automation Server

CancelPrinting Method (Report Object)

ClearError Method (Report Object)

Export Method (Report Object)

Preview Method (Report Object)

PrintOut Method (Report Object)

ReadRecords Method (Report Object)

SelectPrinter Method (Report Object)


Report Object Events

ReadingRecords Event (Report Object)

Start Event (Report Object)

Stop Event (Report Object)


AddGroup Method (Report Object)—CRE Object Model For the Automation Server

The AddGroup method adds a group to the report. ConditionField indicates the field for grouping, Condition indicates a change in a field value that generates a grouping, and SortDirection specifies the direction in which groups are sorted.

Syntax

object.AddGroup GroupN, ConditionField, Condition, SortDirection

Parameters

GroupN | Specifies the number of the group to be added (the position of the group in relation to existing groups). For example, to add a group to the first position, set GroupN to 1
ConditionField | Specifies the field to be grouped. The field can be a database field definition object or the field name.
Condition | Specifies CRGroupCondition (see table below) indicating the grouping condition.
 | Constant | Value
 | crGCAnually | 7
 | crGCAnyValue | 14
 | crGCBiweekly | 2
 | crGCDaily | 0
 | crGCEveryNo | 11
 | crGCEveryYes | 10
 | crGCMonthly | 4
 | crGCNextIsNo | 13
 | crGCNextIsYes | 12
 | crGCQuarterly | 5
 | crGCSEmiAnnually | 6
 | crGCSemimonthly | 3
 | crGCToNo | 9
 | crGCToYes | 8
 | crGCWeekly | 1
SortDirection | Specifies CRSortDirection (see table below) indicating the sort direction for the group (that is, ascending, descending).
 | Constant | Value
 | crAscendingOrder | 1
 | crDescendingOrder | 0
 | crOriginalOrder | 2


CancelPrinting Method (Report Object)

The CancelPrinting method cancels the printing of a report. It corresponds to PECancelPrintJob, of the Crystal Report Engine.

Syntax

object.CancelPrinting


ClearError Method (Report Object)

Sample Code - ClearError Method

The ClearError method clears the last error code or last error string at the report level.

Syntax

object.ClearError


DiscardSavedData Method (Report Object)

The DiscardSavedData method discards any saved data with the report before previewing. It corresponds to , of the Crystal Report Engine.

Syntax

object.DiscardSavedData


Export Method (Report Object)

The Export method exports reports to a format and destination specified with ExportOptions Object.

Syntax

object.Export PromptUser

Parameters

PromptUser (Optional)

Specifies Boolean value indicating if user should be prompted for export options (if you don't want to prompt). All necessary export options have to be set or prompt will be used whether this parameter is set to TRUE or FALSE.


OpenSubreport Method (Report Object)

Sample Code - OpenSubreport Method

Every subreport has a pointer to its parent report. Subreports hold on to their parent reports until they are destroyed. The OpenSubreport method opens a subreport contained in the report and returns a Report Object, corresponding to the named subreport. It corresponds to PEOpenSubreport, of the Crystal Report Engine.

Syntax

set reportvar = object.OpenSubreport (SubreportName)

Parameter

SubreportName

Specifies the file name of the subreport to be opened.

Returns

Report


Preview Method (Report Object)

Sample Code - Preview Method

The Preview method reviews the report and returns the View Object.

Syntax
Set ViewVar = object.Preview (Title, Left, Top, Width, Height,

Style, ParentWindow)

to capture the View object or,

object.Preview Title, Left, Top, Width, Height, Style, ParentWindow

for use without capturing the View object.

Parameters
Title (Optional) | Specifies the string that contains the title that you want to appear on the title bar if you are printing the report to a window.
Left (Optional) | Specifies the x coordinate of the upper left-hand corner of the print window, in pixels.
Top (Optional) | Specifies the y coordinate of the top of the print window, in pixels.
Width (Optional) | Specifies the width of the print window, in pixels.
Height (Optional) | Specifies the height of the print window, in pixels.
Style (Optional) | Specifies the style of the window being created. Style settings can be combined using the bitwise "OR" operator. Select a style from the list that appears with PEOutputToWindow.
Parent Window (Optional) | Specifies the handle to the Parent Window if the print window is a child of that window.
Returns

The View Object, which represents the view created by previewing.


PrintOut Method (Report Object)

Sample Code - PrintOut Method

The PrintOut method prints out the specified pages of the report to the printer selected by using the SelectPrinter Method (Report Object), method. If no printer is selected, the default printer specified in the report will be used.

Syntax
object.PrintOut PromptUser, NumberOfCopies, Collated,

StartPageNumber, StopPageNumber
Parameters
PromptUser (Optional) | Specifies Boolean value indicating if the user should be prompted for printer options.
NumberOfCopies (Optional) | Specifies the number of report copies that you want printed.
Collated (Optional) | Specifies Boolean value specifying whether or not you want the report copies collated.
StartPageNumber (Optional) | Specifies the first page that you want printed.
StopPageNumber (Optional) | Specifies the last page that you want printed.


ReadRecords Method (Report Object)

The ReadRecords method reads records in the report.

Syntax

object.ReadRecords


SelectPrinter Method (Report Object)

The SelectPrinter method selects a different printer for the report. The values associated with the properties of PageSetup Object may change if a call to SelectPrinter method is made.

Syntax

object.SelectPrinter DriverName, PrinterName, PortName

Parameters
DriverName | String that contains the name of the printer driver for the selected printer. See DriverName property of PrinterInfo Object for more information.
PrinterName | String that contains the printer name for the selected printer. See PrinterName property of PrinterInfo Object for more information.
PortName | String that contains the port name for the port to which the selected printer is attached. See PortName property of PrinterInfo Object for more information.


ReadingRecords Event (Report Object)

Sample Code - ReadingRecords Event

The ReadingRecords event occurs when records are read (that is, when a report is previewed, printed, refreshed, etc.). Reading occurs at random intervals, so a different number of reading record events may occur each time the same report is previewed, printed, etc.

Syntax
Event ReadingRecords (ReadRecords As Long, RecordsSelected As Long,
Cancelled As Boolean, Done As Boolean)
Parameters
Cancelled | Specifies Boolean value indicating that record reading was cancelled.
Done | Specifies Boolean value indicating whether record reading is finished.
RecordsRead | Specifies the number of records read to process the report.
RecordsSelected | Specifies the number of records selected to appear in the report.
ReportName | Reserved for future use.
Remarks

This event is enabled by using the ReadingRecordsEventEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information on events, see Object Model Events.


Start Event (Report Object)

Sample Code - Start Event

The Start event occurs when the report starts printing or previewing.

Syntax
Event Start (Destination As CRPrintingDestination,

useDefault As Boolean)
Parameters

Destination | Specifies CRPrintingDestination (see table below) indicating what "destination" the report will be printed to (that is, printer, window, exported, etc.).
 | Constant | Value
 | crFromQuery | 4
 | crToExport | 3
 | crToNoWhere | 0
 | crToPrinter | 2
 | crToWindow | 1
useDefault | Specifies Boolean value indicating if default behavior should occur after user's event code has run (that is, should the report start to print or preview?). |

Remarks

This event is enabled by using the StartStopEventEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events .


Stop Event (Report Object)

Sample Code - Stop Event

The Stop event that occurs when report stops printing/previewing.

Syntax
Event Stop (Destination As CRPrintingDestination,

Status As CRPrintingProgress)
Parameters

Destination | Specifies CRPrintingDestination (see table below) indicating what "destination" the report will be printed to (that is, printer, window, exported, etc.).
 | Constant | Value
 | crFromQuery | 4
 | crToExport | 3
 | crToNoWhere | 0
 | crToPrinter | 2
 | crToWindow | 1
Status | Specifies CRPrintingProgress (see table below) indicating the progress of the report print job (that is, in progress, halted, cancelled, etc.).
 | Constant | Value
 | crPrintingCancelled | 5
 | crPrintingCompleted | 3
 | crPrintingFailed | 4
 | crPrintingHalted | 6
 | crPrintingInProgress | 2
 | crPrintingNotStarted | 1

Remarks

This event is enabled using the StartStopEventEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


ReportObjects Collection

The ReportObjects Collection is a collection of report objects in a section. Report objects can be a field, text, ole, cross-tab, subreport, BLOB field, Box, Graph, or Line objects. Access a specific object in the collection using the Item property.

ReportObjects Collection Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Count | Returns the number of report objects in the collection. | Read only
Item | Returns a report object. Depending on the type of item referenced, this can be a BlobFieldObject Object,FieldObject Object,TextObject Object, OLEObject Object, CrossTabObject Object, SubreportObject Object, BoxObject Object, GraphObject Object, or a LineObject Object. Item has an index parameter that is a numeric, 1-based index (i.e., Item (1)). The items in the collection are indexed in the order they were added to the report. | Read only
Parent | Reference to the Parent object (Section Object). | Read only
Report | Reference to Report Object. | Read only

Remarks

Instead of using the Item property as shown, you can reference a report object directly, for example, ReportObjects.Item(1).


ReportOptions Object

The ReportOptions Object provides properties for manipulating the options available in the report.

ReportOptions Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, this object is associated with. | Read only
CaseInsensitiveSQL Data | Returns/Sets Boolean value indicating if SQL data is case-sensitive. | Read/Write
ConvertDateTime ToDate | Returns/Sets CRConvertDateTimeType (see table below) indicating what datetime fields are to be converted to (that is, string, time, no conversion, etc.). | Read/Write
 | Constant | Value
 | crConvertDateTimeToDate | 1
 | crConvertDateTimeToString | 0
 | crKeepDateTimeType | 2
Property | Description | Read/Write
ConvertNullField ToDefault | Returns/Sets Boolean value indicating if null database fields should be converted to the default value. | Read/Write
HasGroupTree | Returns/Sets Boolean value indicating if the preview window includes the Group Tree. You must also set the HasGroupTree property to TRUE in the PrintWindowOptions Object, to have the Group Tree show in the preview window. | Read/Write
MorePrintEngine ErrorMessages | Returns/Sets Boolean value indicating if more print engine error messages are given at the report level. If they are on by default, you can turn this option off by using this property. | Read only
Report | Read only | Read only
SaveDataWith Report | Returns/Sets Boolean value indicating if data is saved with the report. | Read/Write
SaveSummaries WithReport | Returns/Sets Boolean value indicating if summary values (that is, group, report, cross-tab summaries) are to be saved with the report. You must also set SaveDataWithReport to TRUE. | Read/Write
TranslateDOS Memos | Returns/Sets Boolean value indicating if DOS Memos are translated. | Read/Write
TranslateDOS Strings | Returns/Sets Boolean value indicating if DOS Strings are translated. | Read/Write
UseIndexForSpeed | Returns/Sets Boolean value indicating if indexes are used. | Read/Write
VerifyOnEveryPrint | Returns/Sets Boolean value indicating if data is verified on every print. | Read/Write
ZoomMode | Returns/Sets CRZoomLevel (see table below) indicating what zoom level the preview should initially utilize when opened. | Read/Write
 | Constant | Value
 | crPageWidth | 1
 | crWholePage | 2


ReportSummaryInfo Object

The ReportSummaryInfo Object provides properties for retrieving information and setting options for summary information included in a report (that is, author, title, etc.). A ReportSummaryInfo Object is obtained from the ReportSummaryInfo property of the Report Object.

ReportSummaryInfo Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Author | Returns/Sets string specifying the name of the report author. | Read only
Comments | Returns/Sets string specifying the report comments. | Read/Write
Keywords | Returns/Sets string specifying the report keywords. | Read/Write
Name | Returns application name that created the report. | Read only
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read only
Subject | Returns/Sets string specifying the report subject. | Read only
Template | Returns/Sets string specifying the report template. | Read/Write
Title | Returns/Sets string specifying the report title. | Read/Write


Section Object

Sample Code - Section Object

Report areas contain at least one section. The Section Object includes properties for accessing information regarding a section of your report. This object holds on to a report object, then releases the report object when it is destroyed.

Section Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Height | Returns/Sets the height of the section in twips. | Read/Write
Number | Returns the number associated with the section in the area (that is, if the first section in an area, the number returned is 1). | Read only
Options | Returns SectionOptions Object. | Read only
Parent | Reference to the Parent object (Area Object). | Read only
Report | Reference to Report Object. | Read only
ReportObjects | Returns ReportObjects Collection, a heterogeneous collection of report objects. | Read only
Width | Returns the width of the section in twips. | Read only


SectionOptions Object

The SectionOptions Object represents a section found in a report. A section is a part of a report area that can be formatted separately from other sections in the report. This object provides properties for retrieving information and setting options for a section in your report (that is, background color, new page after, etc.). A SectionOptions Object is obtained from the Options property of the Section Object.

Each report area is comprised of sections that can be formatted independently of each other using the SectionOptions object. These section options are combined with the options set by using the AreaOptions Object, to make up the final appearance of a section and an area of the report. The settings in the AreaOptions object will affect all sections within the area, while settings in the SectionOptions object will affect only the section they are set to.

If there is a conflict of settings between the AreaOptions object and the SectionOptions object, the object with an option set to TRUE will override the setting for the other object. For example, if the AreaOptions object has the KeepTogether property set to TRUE, all sections within the area will have KeepTogether applied, even if the SectionOptions object for a section has KeepTogether set to FALSE. If, however, the AreaOptions object has KeepTogether set to FALSE, but a section within that area has KeepTogether set to TRUE, that section will have the KeepTogether format option applied.

If an area has only a single section, all options will be combined between both the AreaOption object and the SectionOptions object. All TRUE settings set in either object will result in a TRUE setting for the entire area and section. While changing format options for areas and sections in reports, be sure to keep track of settings in both the AreaOptions and SectionOptions objects.

SectionOptions Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
BackColor | Returns/Sets CRColor (see table below) indicating OLE color. You can use CRColor values or declare your own colors by using OLE colors (that is, by using RGB function). | Read/Write
 | Constant | Value
 | crAqua | 16776960
 | crBlack | 0
 | crBlue | 16711680
 | crFuchsia | 16711935
 | crGray | 8421504
 | crGreen | 32768
 | crLime | 65280
 | crMaroon | 128
 | crNoColor | -1
 | crOlive | 32896
 | crPurple | 8388736
 | crRed | 255
 | crSilver | 12632256
 | crTeal | 8421376
 | crWhite | 16777215
 | crYellow | 65536
BackColor Formula | Returns/Sets string specifying a formula for conditionally setting the background color of a section. | Read/Write
FreeForm Placement | Returns/Sets Boolean value indicating if section has free form placement. | Read/Write
KeepTogether | Returns/Sets Boolean indicating if section keeps together (doesn't break) across pages | Read/Write
KeepTogether Formula | Returns/Sets string specifying the formula for conditionally setting if a section should keep together (doesn't break) across pages. | Read/Write
NewPageAfter | Returns/Sets Boolean value indicating if there is a new page after the section is printed. | Read/Write
NewPageAfter Formula | Returns/Sets string specifying the formula for conditionally setting the report to start a new page after this section is printed. | Read/Write
NewPageBefore | Returns/Sets Boolean value indicating if there is a new page before the section is printed. | Read/Write
NewPageBefore Formula | Returns/Sets string specifying the formula for conditionally setting the report to start a new page before this section is printed. | Read/Write
Parent | Reference to the Parent object (Section Object). | Read only
PrintAtBottom OfPage | Returns/Sets Boolean indicating if the section is printed at the bottom of the page. | Read/Write
PrintAtBottom OfPageFormula | Returns/Sets string specifying formula for conditionally printing section at the bottom of the page. | Read/Write
Report | Reference to Report Object. | Read only
ResetPage NumberAfter | Returns/Sets Boolean value indicating if the page number will be reset after the section is printed. | Read/Write
ResetPage NumberAfter Formula | Returns/Sets string specifying the formula for conditionally resetting the page number. | Read/Write
SuppressIfBlank | Returns/Sets Boolean value indicating if the section is suppressed when containing no data. | Read/Write
SuppressIf BlankFormula | Returns/Sets string specifying the formula for conditionally suppressing a section when containing no data. | Read/Write
UnderlaySection | Returns/Sets Boolean value indicating if the section underlays the following sections. | Read/Write
UnderlaySection Formula | Returns/Sets string specifying the formula for conditionally underlaying a section. | Read/Write
Visible | Returns/Sets Boolean value indicating whether a section is shown (visible). | Read/Write
VisibleFormula | Returns/Sets string specifying the formula for conditionally showing (making visible) a section. | Read/Write


Sections Collection

Sections can come from either the Report Object, or Area Object. The Sections Collection is a collection of section objects. Access a specific Section Object in the collection by using the Item property.

  • When from the Report Object, the sections object will contain all the sections in the report.
  • When from the Area Object, the sections object will contain all the sections in the area only.

Sections Collection Properties
Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Count | Returns the number of section in the collection. | Read only
Item | Returns Section Object. Item has an index parameter that can be either a string reference to the area section (that is, for areas with one section: "RH", "PH", "GHn", "D", "GFn", "PF", or "RF") or a numeric, 1-based index (that is, Item (1)) for the Report Header area. Numeric index for sections starts at 1 for first section in the area/report and continues in order of appearance. If the area has multiple sections, they are represented using a lowercase letter (that is, "Da", "Db", etc.). | Read only
Parent | Reference to the Parent object (Report Object, or Area Object). | Read only
Report | Reference to Report Object. | Read only

Remarks

Instead of using the Item property as shown, you can reference a section directly (for example, Sections ("Da")).


SortField Object

Sample Code - SortField Object

The SortField Object includes properties for accessing information for record or group sort fields. It holds on to Report object, then releases the report object when destroyed. This object has an index instance variable to indicate its index.

SortField Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, this object is associated with. | Read only
Field | Returns/Sets DatabaseFieldDefinition Object, which specifies the sort field used in the report. | Read/Write
Parent | Reference to the Parent object (Report Object). | Read only
Report | Reference to Report Object. | Read/Write
SortDirection | Returns/Sets CRSortDirection (see table below) indicating the direction the group/records are sorted in. | Read/Write
 | Constant | Value
 | crAscendingOrder | 1
 | crDescendingOrder | 0
 | crOriginalOrder | 2
 | crSpecifiedOrder (Read only - this value cannot be set.) | 3


SortFields Collection

The SortFields Collection is a collection of sort fields that can be either a record sort field, or a group sort field. Access a specific SortField Object in the collection by using the Item property.

SortFields Collection Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Count | Returns the number of sort fields in the collection. | Read only
Item | Returns SortField Object. Item has an index parameter that is a numeric, 1-based index (that is, Item (1)). The sort fields in the collection are indexed in the order that they were added as sort fields in the report. | Read only
Parent | Reference to the Parent object Report Object. | Read only
Report | Reference to Report Object. | Read only

Remarks

Instead of using the Item property as shown, you can reference a sort field directly (for example, SortFields(1)).


SortFields Collection Methods

Add Method (SortFields Collection)

Delete Method (SortFields Collection)


Add Method (SortFields Collection)

The Add method adds a record or group sort field.

Syntax

object.Add SortDirection, Field

ParametersL

SortDirection | Specifies CRSortDirection (see table below) indicating the direction in which the field data should be sorted (that is, ascending, descending, etc.).
 | Constant | Value
 | crAscendingOrder | 1
 | crDescendingOrder | 0
 | crOriginalOrder | 2
Field | Specifies the field definition or field name.

Returns

SortField


Delete Method (SortFields Collection)

The Delete method deletes a record or group sort field.

Syntax

object.Delete Index

Parameter

Index

Specifies the 1-based number indicating which sort field in the collection should be deleted. The first sort field is sort field 1.


SpecialVarFieldDefinition Object

The SpecialVarFieldDefinition Object provides properties for retrieving information and setting options for a special field found in your report (that is, last modification date, print date, etc.). A SpecialVarFieldDefinition Object is obtained from the Field property of the FieldObject Object.

SpecialVarFieldDefinition Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Kind | Returns CRFieldKind (see table below) that specifies the "kind" of field (database, summary, formula, etc.). | Read only
 | Constant | Value
 | crDatabaseField | 1
 | crFormulaField | 2
 | crGroupNameField | 5
 | crParameterField | 6
 | crSpecialVarField | 4
 | crSummaryField | 3
Name | Returns the name of the special var field. | Read only
NumberOfBytes | Returns the number of bytes required to store the field data in memory. | Read only
Parent | Reference to the Parent object Report Object. | Read only
Report | Reference to Report Object. | Read only
SpecialVarType | Returns CRSpecialVarType (see table below) value indicating the type of special field (that is, ReportTitle, PageNumber, etc.). | Read only
 | Constant | Value
 | crSVTDataDate | 7
 | crSVTDataTime | 8
 | crSVTGroupNumber | 6
 | crSVTModificationDate | 2
 | crSVTModificationTime | 3
 | crSVTPageNumber | 5
 | crSVTPrintDate | 0
 | crSVTPrintTime | 1
 | crSVTRecordNumber | 4
 | crSVTReportComments | 11
 | crSVTReportTitle | 10
 | crSVTTotalPageCount | 9
Property | Description | Read/Write
ValueType | Returns CRFieldValueType (see table below), which specifies the "type" of value found in the field. | Read only
 | Constant | Value
 | crBitmapField | 17
 | crBlobField | 15
 | crBooleanField | 9
 | crChartField | 21
 | crCurrencyField | 8
 | crDateField | 10
 | crDateTimeField | 16
 | crIconField | 18
 | crInt16sField | 3
 | crInt16uField | 4
 | crInt32sField | 5
 | crInt32uField | 6
 | crInt8sField | 1
 | crInt8uField | 2
 | crNumberField | 7
 | crOleField | 20
 | crPersistentMemoField | 14
 | crPictureField | 19
 | crStringField | 12
 | crTimeField | 11
 | crTransientMemoField | 13
 | crUnknownField | 22


SubreportObject Object

Sample Code - SubReportObject Object

The SubreportObject Object represents a subreport found in a report. A subreport is a free-standing or linked report found within the main report. This object provides properties for retrieving information on the subreport (that is, name, etc.).

Subreport Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Kind | Returns CRObjectKind (see table below) that specifies what "kind" of object (that is, box, cross-tab, field). | Read only
 | Constant | Value
 | crBlobFieldObject | 9
 | crBoxObject | 4
 | crCrossTabObject | 8
 | crFieldObject | 1
 | crGraphObject | 7
 | crLineObject | 3
 | crOleObject | 6
 | crSubreportObject | 5
 | crTextObject | 2
Name | Returns the name of the subreport. | Read only
Parent | Reference to the Parent object (Section Object). | Read only
Report | Reference to Report Object. | Read only


SummaryFieldDefinition Object

The SummaryFieldDefinition Object represents the summary used in a cross-tab, group, or report, or the summary used in a group or cross-tab graph.

SummaryFieldDefinition Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
CrossTabObject | Returns CrossTabObject Object, that contains the summary field. This property is for cross-tab summary fields only; if the summary field is not from a cross-tab you will get an exception. | Read only
FooterArea | Returns Area Object, indicating the Group/Report Footer area of the summary. This property is for group or report summary fields only; if the summary is from a cross-tab you will get an exception when using this property. | Read only
ForCrossTab | Returns Boolean value indicating if summary is used in a cross-tab. | Read only
HeaderArea | Returns Area Object, indicating the Group/Report Header area of the summary. If the summary is from a cross-tab you will get an exception when using this property. | Read only
Kind | Returns CRFieldKind, which specifies what "kind" of field (database, summary, formula, etc.). | Read only
 | Constant | Value
 | crDatabaseField | 1
 | crFormulaField | 2
 | crGroupNameField | 5
 | crParameterField | 6
 | crSpecialVarField | 4
 | crSummaryField | 3
Property | Description | Read/Write
Name | Returns the name of the summary field for a group or report summary field. Cross-tab summaries do not have a unique name, so an empty string will be returned. | Read only
NumberOf Bytes | Returns the number of bytes required to store the field data in memory. | Read only
Parent | Reference to the Parent object Report Object. | Read only
Report | Reference to Report Object. | Read only
SummaryType | Returns value of type CRSummaryType (see table below) indicating the type of summary (that is, sum, average, etc.). | Read only
 | Constant | Value
 | crSTAverage | 1
 | crSTCount | 6
 | crSTDisctintCount | 9
 | crSTMaximum | 4
 | crSTMinimum | 5
 | crSTPopStandardDeviation | 8
 | crSTPopVariance | 7
 | crSTSampleStandardDeviation | 3
 | crSTSampleVariance | 2
 | crSTSum | 0
ValueType | Returns CRFieldValueType (see table below), which specifies the "type" of value found in the field. | Read only
 | Constant | Value
 | crBitmapField | 17
 | crBlobField | 15
 | crBooleanField | 9
 | crChartField | 21
 | crCurrencyField | 8
 | crDateField | 10
 | crDateTimeField | 16
 | crIconField | 18
 | crInt16sField | 3
 | crInt16uField | 4
 | crInt32sField | 5
 | crInt32uField | 6
 | crInt8sField | 1
 | crInt8uField | 2
 | crNumberField | 7
 | crOleField | 20
 | crPersistentMemoField | 14
 | crPictureField | 19
 | crStringField | 12
 | crTimeField | 11
 | crTransientMemoField | 13
 | crUnknownField | 22


SummaryFieldDefinitions Collection

The SummaryFieldDefinitions Collection is a collection of summary field definitions. They can be from either CrossTabObject Object, or Report Object. Access a specific SummaryFieldDefinition Object in the collection by using the Item property.

SummaryFieldDefinitions Collection Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Count | Returns the number of summary fields in the collection. | Read only
Item | Returns SummaryFieldDefinition Object. Item has an index parameter that is a numeric, 1-based index (that is, Item (1)). The items in the collection are indexed in the order that they were added to the report. | Read only
Parent | Reference to the Parent object CrossTabObject Object,or Report Object). | Read only
Report | Reference to Report Object. | Read only

Remarks

Instead of using the Item property as shown, you can reference a summary field directly, for example, SummaryFieldDefinitions (1).


TextObject Object

Sample Code - TextObject Object

The Text Object represents a text object found in a report. This object provides properties for retrieving information and setting options for a text object in your report.

TextObject Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Kind | Returns CRObjectKind (see table below) that specifies what "kind" of object (that is, box, cross-tab, field). | Read only
 | Constant | Value
 | crBlobFieldObject | 9
 | crBoxObject | 4
 | crCrossTabObject | 8
 | crFieldObject | 1
 | crGraphObject | 7
 | crLineObject | 3
 | crOleObject | 6
 | crSubreportObject | 5
 | crTextObject | 2
Parent | Reference to the Parent object (Section Object). | Read only
Report | Reference to Report Object. | Read only


TrackCursorInfo Object

The TrackCursorInfo Object provides properties/methods for tracking the position of the cursor in the report and for setting cursor icons for the specified areas of the report. Cursor icon availability will vary, depending on your development platform.

TrackCursorInfo Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
DetailAreaCursor | Returns/Sets CRTrackCursor (see table below GroupAreaFieldCursor property) indicating what type of cursor is to be displayed when the cursor is moved over the Details Area. Check your operating system documentation for a list of cursors available on your system. If you choose an unavailable cursor, the default (arrow) cursor will be used. | Read/Write
DetailAreaField Cursor | Returns/Sets CRTrackCursor (see table below GroupAreaFieldCursor property) indicating what type of cursor is to be displayed when the cursor is moved over fields in the Details Area. Check your operating system documentation for a list of cursors available on your system. If you choose an unavailable cursor, the default (arrow) cursor will be used. | Read/Write
GraphCursor | Returns/Sets CRTrackCursor (see table below GroupAreaFieldCursor property) indicating what type of cursor is to be displayed when the cursor is moved over a graph. Check your operating system documentation for a list of cursors available on your system. If you choose an unavailable cursor, the default (arrow) cursor will be used. | Read/Write
GroupAreaCursor | Returns/Sets CRTrackCursor (see table below GroupAreaFieldCursor property) indicating what type of cursor is to be displayed when the cursor is moved over the Group Area. Check your operating system documentation for a list of cursors available on your system. If you choose an unavailable cursor, the default (arrow) cursor will be used. | Read/Write
GroupAreaField Cursor | Returns/Sets CRTrackCursor (see table below) indicating what type of cursor is to be displayed when the cursor is moved over fields in the Group Area. Check your operating system documentation for a list of cursors available on your system. If you choose an unavailable cursor, the default (arrow) cursor will be used. | Read/Write
 | Constant | Value
 | crAppStartingCursor | 12
 | crArrowCursor | 1
 | crCrossCursor | 2
 | crDefaultCursor | 0
 | crHelpCursor | 13
 | crIBeamCursor | 3
 | crIconCursor | 15
 | crMagnifyCursor | 99
 | crNoCursor | 10
 | crSizeAllCursor | 5
 | crSizeCursor | 14
 | crSizeNESWCursor | 7
 | crSizeNSCursor | 9
 | crSizeNWSECursor | 6
 | crSizeWECursor | 8
 | crUpArrowCursor | 4
 | crWaitCursor | 11
Property | Description | Read/Write
Parent | Reference to the Parent object PrintWindowOptions Object). | Read only
Report | Reference to Report Object. | Read only


View Object

Sample Code - View Object

The View Object is returned when previewing a report. A View represents a single view on the report. A View always lives inside a window. While there are two types of views available in Crystal Reports (Design and Preview), the Crystal Report Engine supports only the Preview window view. This object holds on to the Report Object, then releases it when it is destroyed.

A View object is created when a report is first generated and displayed in the Preview window. If a user drills down on summary values or on graph data, additional View objects are created as additional drill-down views appear in the Preview window. Each Preview tab that appears in the Preview window represents a separate View object. Only the View object for the currently active Preview tab can be manipulated at runtime.

View Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
DisplayedPage Number | Returns the page number currently displayed in the current view. You will receive an incorrect result if you try to obtain this value immediately after using a method such as ShowNextPage Method (View Object), that causes a change to the Preview window. Call the Visual Basic function, DoEvents (see Visual Basic documentation for more information) before requesting the page number display. | Read only
Parent | Reference to the Parent object Window Object). | Read only
Report | Reference to Report Object. | Read only


View Object Methods

Close Method (View Object)

Export Method (View Object)

NextMagnification Method (View Object)

PrintOut Method (View Object)

ShowFirstPage Method (View Object)

ShowLastPage Method (View Object)

ShowNextPage Method (View Object)

ShowNthPage Method (View Object)

ShowPreviousPage Method (View Object)

ZoomPreviewWindow Method (View Object)


Close Method (View Object)

The Close method closes the main view. Because only one view is supported, this method will apply to the main view (preview) only. The Preview window will be closed.

Syntax

object.Close


Export Method (View Object)

The Export method exports the main view to selected format and destination; prompts for options. Because only one view is supported, this method will apply to the main view (preview) only.

Syntax

object.Export


NextMagnification Method (View Object)

Sample Code - NextMagnification Method

The NextMagnification method shows the view at the "next magnification" in the series (that is, page width -- full page -- 100%). Because only one view is supported, this method will apply to the main view (preview) only.

Syntax

object.NextMagnification


PrintOut Method (View Object)

The PrintOut method sends the view to printer specified in the report to be printed. Because only one view is supported, this method will apply to the main view (preview) only.

Syntax

object.PrintOut


ShowFirstPage Method (View Object)

The ShowFirstPage method shows the first page of the view. Because only one view is supported, this method will apply to the main view (preview) only.

Syntax

object.ShowFirstPage


ShowLastPage Method (View Object)

The ShowLastPage method shows the last page of the view. Because only one view is supported, this method will apply to the main view (preview) only.

Syntax

object.ShowLastPage


ShowNextPage Method (View Object)

The ShowNextPage method shows the next page of the view. Because only one view is supported, this method will apply to the main view (preview) only.

Syntax

object.ShowNextPage


ShowNthPage Method (View Object)

The ShowNthPage method shows the nth page of the view. Because only one view is supported, this method will apply to the main view (preview) only.

Syntax

object.ShowNthPage (PageNumber)

Parameter

PageNumber

Specifies the number of the page to be shown.


ShowPreviousPage Method (View Object)

The ShowPreviousPage method shows the previous page of the view. Because only one view is supported, this method will apply to the main view (preview) only.

Syntax

object.ShowPreviousPage


ZoomPreviewWindow Method (View Object)

The ZoomPreviewWindow method zooms the view in and out, showing the report as a percentage of the full size of the report page. Because only one view is supported, this method will apply to the main view (preview) only.

Syntax

object.ZoomPreviewWindow (ZoomLevel)

Parameter

ZoomLevel

Specifies the percentage of magnification for the view (for example, 50%, 75%, etc.).


Views Collection

The Views Collection is a collection of views for a report. A View Object, is created when a report is first generated and displayed in the Preview window. If a user drills-down on summary values or on graph data, additional View objects are created as additional drill-down views appear in the Preview window. Each Preview tab that appears in the Preview window represents a separate View object. Only the View object for the currently active Preview tab can be manipulated at runtime.

The Views collection contains all View objects for the report. However, since only the currently active view can be accessed, the Count property will always contain a value of 1. The currently active View object can be accessed by passing 1 to the Item property. For example:

Set activeView = viewsCollection.Item(1)

Views Collection Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
Count | Returns the number of views in the collection. Because only one view is supported (preview), this number should always be 1. | Read only
Item | Returns View Object. Item has an index parameter that is a numeric, 1-based index (that is, Item (1) returns the main view). Because only a single View object can be accessed at any time, the currently active view, any index other than 1 will return an error. | Read only
Parent | Reference to the Parent object Window Object). | Read only
Report | Reference to Report Object. | Read only

Remarks

Instead of using the Item property as shown, you can reference a view directly (for example, Views (1)).


Window Object

Sample Code - Window Object

The Window Object is obtained through View.Parent. It is the window that previews the report. A Window represents the highest-level window associated with a single report. In the Crystal Report Engine and the Crystal Report Automation Server, it is a preview window.

Window Object Properties

Property | Description | Read/Write
Application | Returns a reference to the Application Object, that this object is associated with. | Read only
ControlsVisible | Returns/Sets Boolean value indicating if window controls are visible in the preview window. | Read/Write
Parent | Reference to the Parent object Report Object). | Read only
Report | Reference to Report Object. | Read only
Views | Returns Views Collection, a collection of views in the window. | Read only
WindowHandle | Returns the handle of the window. | Read only


Window Object Methods

Close Method (Window Object)


Window Object Events

ActivatePrintWindow Event (Window Object)

CancelButtonClicked Event (Window Object)

CloseButtonClicked Event (Window Object)

ClosePrintWindow Event (Window Object)

DeactivatePrintWindow Event (Window Object)

DrillOnDetail Event (Window Object)

DrillOnGroup Event (Window Object)

ExportButtonClicked Event (Window Object)

FirstPageButtonClicked Event (Window Object)

GroupTreeButtonClicked Event (Window Object)

LastPageButtonClicked Event (Window Object)

NextPageButtonClicked Event (Window Object)

PrevPageButtonClicked Event (Window Object)

PrintButtonClicked Event (Window Object)

RefreshButtonClicked Event (Window Object)

SearchButtonClicked Event (Window Object)

ShowGroup Event (Window Object)

ZoomLevelChanging Event (Window Object)


Close Method (Window Object)

The Close method closes the window, and consequently, all views in the window.

Syntax

object.Close


ActivatePrintWindow Event (Window Object)

Sample Code - ActivatePrintWindow Event

The ActivatePrintWindow event occurs when the print window is activated (that is, received focus from another window).

Syntax

Event ActivatePrintWindow ()

Remarks

This event is enabled by using the ActivatePrintWindowEventEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


CancelButtonClicked Event (Window Object)

Sample Code - CancelButtonClicked Event

The CancelButtonClicked event occurs when the Cancel button is clicked.

Syntax

Event CancelButtonClicked (useDefault As Boolean)

Parameter

useDefault

Specifies Boolean value indicating whether the default settings should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want the cancel button to cancel moving to the last page or processing the report).

Remarks

Before enabling this event, the HasCancelButton property of the PrintWindowOptions Object, must be set to TRUE. This event is enabled by using the PrintWindowButtonEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


CloseButtonClicked Event (Window Object)

Sample Code - CloseButtonClicked Event

The CloseButtonClicked event occurs when the Close button is clicked, either to close a view or the entire preview window itself.

Syntax
Event CloseButtonClicked (ViewIndex As Integer,

useDefault As Boolean)
Parameters

ViewIndex | Specifies the index of the view that is to be closed.
useDefault | Specifies Boolean value indicating whether the default settings should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want the view/preview window to close).

Remarks

Before enabling this event, the HasCloseButton property of the PrintWindowOptions Object, must be set to TRUE. This event is enabled by using the PrintWindowButtonEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


ClosePrintWindow Event (Window Object)

Sample Code - ClosePrintWindow Event

The ClosePrintWindow event occurs when the print window is closed.

Syntax

Event ClosePrintWindow (useDefault As Boolean)

Parameter

useDefault

Specifies Boolean value indicating whether the default settings should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want the print window to close).

Remarks

This event is enabled by using the ClosePrintWindowEventEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


DeactivatePrintWindow Event (Window Object)

Sample Code - DeactivatePrintWindow Event

The DeactivatePrintWindow event occurs when the print window is deactivated (that is, when any other window takes the focus from the print window).

Syntax

Event DeactivatePrintWindow ()

Remarks

This event is enabled by using the ActivatePrintWindowEventEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


DrillOnDetail Event (Window Object)

Sample Code - DrillOnDetail Event

The DrillOnDetail event occurs when you drill down on a field in the Details area of the report.

Syntax
Event DrillOnDetail (FieldValues, SelectedFieldIndex As Long,

useDefault As Boolean)
Parameters

FieldValues | Specifies an array of FieldValue objects (see FieldValue Object). Each object contains information about a single field for the Detail record that was drilled down on. FieldValues may contain database field values, formula field values and summary field values, and group name field values of the group that the record belongs to.
SelectedFieldIndex | Specifies the selected field index in the array that points to the actual FieldValue. If no field is selected, 0 is returned.
useDefault | Specifies Boolean value indicating whether the default settings should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want drill down to occur).
ReportName | Reserved for future use.

Remarks

Before enabling this event, the CanDrillDown property of the PrintWindowOptions Object, must be set to TRUE. For more information, see Object Model Events.


DrillOnGroup Event (Window Object)

Sample Code - DrillOnGroup Event

The DrillOnGroup event occurs when drilling down (double-clicking) on a group field in the preview window.

Syntax
Event DrillOnGroup (GroupNameList, DrillType As CRDrillType,

useDefault As Boolean)
Parameters

GroupNameList | Specifies an array indicating the path to the group that was drilled down on (separated by "/").
DrillType | Specifies CRDrillType (see table below) indicating what type of drill- down occurred.
 | Constant | Value
 | crDrillOnGraph | 2
 | crDrillOnGroup | 0
 | crDrillOnGroupTree | 1
useDefault | Specifies Boolean value indicating whether the default settings should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want drill-down to occur).
ReportName | Reserved for future use.

Remarks

Before enabling this event, the CanDrillDown property of the PrintWindowOptions Object, must be set to TRUE. This event is enabled by using the GroupEventEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


ExportButtonClicked Event (Window Object)

Sample Code - ExportButtonClicked Event

The ExportButtonClicked event occurs when the Export button is clicked.

Syntax

Event ExportButtonClicked (useDefault As Boolean)

Parameter

useDefault

Specifies Boolean value indicating whether the default settings should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want the Export dialog box to appear).

Remarks

Before enabling this event, the HasExportButton property of the PrintWindowOptions Object, must be set to TRUE. This event is enabled by using the PrintWindowButtonEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


FirstPageButtonClicked Event (Window Object)

Sample Code - FirstPageButtonClicked Event

The FirstPageButtonClicked event occurs when the button, that navigates through the report to the first page, is clicked.

Syntax

Event FirstPageButtonClicked (useDefault As Boolean)

Parameter

useDefault

Specifies Boolean value indicating whether the default settings should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want to go to the first page).

Remarks

Before enabling this event, the HasNavigationControls property of the PrintWindowOptions Object, must be set to TRUE. This event is enabled by using the PrintWindowButtonEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


GroupTreeButtonClicked Event (Window Object)

Sample Code - GroupTreeButtonClicked Event

The GroupTreeButtonClicked event occurs when the Group Tree button is clicked to show/hide the Group Tree in the preview window.

Syntax

Event GroupTreeButtonClicked (Visible As Boolean)

Parameters

Visible

Specifies Boolean value indicating whether the Group Tree is visible/hidden after clicking the button.

Remarks

Before enabling this event, the HasGroupTree property of the PrintWindowOptions Object, and the HasGroupTree property of the ReportOptions Object must be set to TRUE. This event is enabled by using the GroupEventEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


LastPageButtonClicked Event (Window Object)

Sample Code - LastPageButtonClicked Event

The LastPageButtonClicked event occurs when the button, that navigates through the report to the last page, is clicked.

Syntax

Event LastPageButtonClicked (useDefault As Boolean)

Parameter

useDefault

Specifies Boolean value indicating whether the default settings should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want to go to the last page).

Remarks

Before enabling this event, the HasNavigationControls property of the PrintWindowOptions Object, must be set to TRUE. This event is enabled by using the PrintWindowButtonEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


NextPageButtonClicked Event (Window Object)

Sample Code - NextPageButtonClicked Event

The NextPageButtonClicked event occurs when the button, that navigates through the report to the next page, is clicked.

Syntax

Event NextPageButtonClicked (useDefault As Boolean)

Parameter

useDefault

Specifies Boolean value indicating whether the default values should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want to go to the next page).

Remarks

Before enabling this event, the HasNavigationControls property of the PrintWindowOptions Object, must be set to TRUE. This event is enabled by using the PrintWindowButtonEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


PrevPageButtonClicked Event (Window Object)

Sample Code - PrevPageButtonClicked Event

The PrevPageButtonClicked event occurs when the button, which navigates through the report to the previous page, is clicked.

Syntax

Event PrevPageButtonClicked (useDefault As Boolean)

Parameters

useDefault

Specifies Boolean value indicating whether the default values should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want to go to the previous page).

Remarks

Before enabling this event, the HasNavigationControls property of the PrintWindowOptions Object, must be set to TRUE. This event is enabled by using the PrintWindowButtonEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


PrintButtonClicked Event (Window Object)

Sample Code - PrintButtonClicked Event

The PrintButtonClicked event occurs when the Print button is clicked.

Syntax

Event PrintButtonClicked (useDefault As Boolean)

Parameters

useDefault

Specifies Boolean value indicating whether the default settings should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want the Print dialog box to appear).

Remarks

Before enabling this event, the HasPrintButton property of the PrintWindowOptions Object, must be set to TRUE. This event is enabled by using the PrintWindowButtonEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


PrintSetupButtonClicked Event (Window Object)

Sample Code - PrintSetupButtonClicked Event

The PrintSetupButtonClicked event occurs when the Print Setup button is clicked.

Syntax

Event PrintSetupButtonClicked (useDefault As Boolean)

Parameters

useDefault

Specifies Boolean value indicating whether the default setting should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want the Printer Setup dialog box to appear).

Remarks

Before enabling this event, the HasPrintSetupButton property of the PrintWindowOptions Object, must be set to TRUE. This event is enabled by using the PrintWindowButtonEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


RefreshButtonClicked Event (Window Object)

Sample Code - RefreshButtonClicked Event

The RefreshButtonClicked event occurs when the Refresh button is clicked.

Syntax

Event RefreshButtonClicked (useDefault As Boolean)

Parameters

useDefault

Specifies Boolean value indicating whether the default setting should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want the report to refresh).

Remarks

Before enabling this event, the HasRefreshButton property of the PrintWindowOptions Object, must be set to TRUE. This event is enabled by using the PrintWindowButtonEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


SearchButtonClicked Event (Window Object)

Sample Code - SearchButtonClicked Event

The SearchButtonClicked event occurs when the Search button is clicked.

Syntax
Event SearchButtonClicked (SearchString As String,

useDefault As Boolean)
Parameters

SearchString | Specifies the string entered by the user that will be searched for.
useDefault | Specifies Boolean value indicating whether the default settings should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want the search for the string to occur).

Remarks

Before enabling this event, the HasSearchButton property of the PrintWindowOptions Object, must be set to TRUE. This event is enabled by using the PrintWindowButtonEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


ShowGroup Event (Window Object)

Sample Code - ShowGroup Event

The ShowGroup event occurs when you click a group in the Group Tree.

Syntax

Event ShowGroup (GroupNameList, useDefault As Boolean)

Parameters

GroupNameList | Specifies an array indicating the path to the group that was drilled down on (separated by "/").
useDefault | Specifies Boolean value indicating whether the default settings should be used. Assign useDefault = FALSE if not using default behavior defined in CPEAUT (that is, if you do not want the group that the user clicked on to be shown in the preview window).
ReportName | Reserved for future use.

Remarks

Before enabling this event, the HasGroupTree property of the PrintWindowOptions Object, and the HasGroupTree property of the ReportOptions Object must be set to TRUE. This event is enabled by using the GroupEventEnabled property of the EventInfo Object, obtained through the EventInfo property of the Report Object. For more information, see Object Model Events.


ZoomLevelChanging Event (Window Object)

Sample Code - ZoomLevelChanging Event

The ZoomLevelChanging event occurs when the zoom level of the report preview is changed.

Syntax
Event FirstPageButtonClicked (ZoomLevel As Integer)
Parameters

ZoomLevel | Specifies integer indicating the percentage of the magnification for viewing the report. Can be CRZoomLevel (see table below) for Page Width and Whole Page. Otherwise, indicate zoom level percentage as an integer.
 | Constant | Value
 | crPageWidth | 1
 | crWholePage | 2

Remarks

Before enabling this event, the HasZoomControl property of the PrintWindowOptions Object, must be set to TRUE. For more information, see Object Model Events.


Error Codes

Related topics:

Automation Server Error Codes

Report Engine Error Codes


Automation Server Error Codes

The Crystal Report Engine Automation Server generates the following error codes, as needed:

Value | Error Code | Description
30001 | CPEAUT_STANDARD_OUTOFMEMORY | There is not enough memory to complete the action.
30002 | CPEAUT_STANDARD_INVALDHANDLE | A handle that is invalid has been specified or does not exist.
30003 | CPEAUT_STANDARD_INVALIDPOINTER | A pointer that is invalid has been specified or does not exist.
30004 | CPEAUT_STANDARD_BADINDEX | An invalid (bad) value has been specified for an index.
30005 | CPEAUT_STANDARD_TYPEMISMATCH | Wrong data type was used.
30006 | CPEAUT_STANDARD_UNKNOWNNAME | The specified name cannot be found in the report.
30007 | CPEAUT_STANDARD_MEDIUMFULL | The storage medium (disk drive) is full.
30008 | CPEAUT_STANDARD_NOTIMPL | Internal error.
30009 | CPEAUT_ERR_NOTGROUPAREA | A group area was expected, but the area specified was not a group area.
30010 | CPEAUT_ERR_STRINGOUTOFRANGE | The string value passed is out of the range of possible values.
30011 | CPEAUT_ERR_NODATABASE | There is no database available.
30012 | CPEAUT_ERR_INVALIDENUMVALUE | An invalid enumerated value has been set.
30013 | CPEAUT_ERR_NOTDETAILAREA | A details area was expected, but the area specified was not a details area.
30014 | CPEAUT_ERR _NOTAREASECTIONCOLLECTION | The object specified is not an Areas or Sections collection.
30015 | CPEAUT_ERR_32NOTSUPPORTED | A 32-bit-only feature has been evoked in an environment that does not support it.
30016 | CPEAUT_ERR_INVALIDKEY | A key that is invalid or does not exist has been specified.
30017 | CPEAUT_ERR_FEATURENOTENABLED | A feature has been evoked that is not yet enabled.
30018 | CPEAUT_ERR_DATABASELINKEXIST | An error has occurred due to the database links.
30019 | CPEAUT_ERR_CREATETEMPFILEFAILED | Creation of a temporary file has been unsuccessful.
30020 | CPEAUT_ERR_RENDERTOHTMLFAILED | Rendering to using RenderHTML Method (Page Object), HTML has been unsuccessful.


Report Engine Error Codes

The Crystal Report Engine Automation Server will also report error codes passed to it from the Crystal Report Engine API. The values of these codes are identical to the Report Engine error code value plus 20000. For example, the value of the Report Engine error PE_ERR_NOTENOUGHMEMORY is 500. The value of the equivalent error reported by the automation server is 20500.


Crystal ActiveX Control Reference

The Crystal ActiveX Control provides an easy to use interface for adding the basic functionality of Crystal Reports to your application. In this section you will find detailed information on properties, methods, and error messages.

Click the appropriate link to jump to that section:

  • Overview of Section Codes
  • ActiveX Controls Properties
  • ActiveX Controls Methods
  • ActiveX Controls Error Messages


Overview of Section Codes

When a section code is required, use the following syntax to supply the values the program needs in order to generate the code:

section type.group.section number

Section type

Section | Section type
Report Header Section | REPORTHDR
Page Header Section | PAGEHDR
Group Header Section | GROUPHDR
Detail Section | DETAIL
Group Footer Section | GROUPFTR
Report Footer Section | REPORTFTR
Page Footer Section | PAGEFTR

If the report contains one or more groups and you are specifying a group section, use an integer to specify the group of interest (the first group is Group 0, the second is Group 1, and so forth).

Note: If you are specifying the section code for anything other than a group section, use 0 for this parameter.

Section

If an area contains more than one section, use an integer to specify the section of interest (the first section in an area is Section 0, the second is Section 1, and so forth).

Example section codes
Specifying the only (or the first) section in a non-group area

REPORTHDR.0.0

«The first Report Header section.»

Specifying one of several sections in a non-group area

If a report has multiple Detail sections and you want to specify the fourth Detail section, you can specify that section as:

DETAIL.0.3

«The fourth Detail section.»

Specifying the only (or the first) section in a group area

GROUPHDR.0.0

«The first section in the first Group Header area.»

Specifying one of several sections in a group area

GROUPFTR.2.1

«The second section in the third Group Footer area.»


ActiveX Controls Properties

Action

BoundReportFooter

BoundReportHeading

Connect

CopiesToPrinter

DataFiles

DataSource

Destination

DetailCopies

DialogParentHandle

DiscardSavedData

EMailCCList

EMailMessage

EMailSubject

EMailToList

EMailVIMBCCList

ExchangeFolder

ExchangePassword

ExchangeProfile

Formulas

GraphData

GraphOptions

GraphText

GraphType

GroupCondition

GroupSelectionFormula

GroupSortFields

LastErrorNumber

LastErrorString

LogOnInfo

MarginBottom

MarginLeft

MarginRight

MarginTop

ParameterFields

Password

PrintDay

PrinterCollation

PrinterCopies

PrinterDriver

PrinterName

PrinterPort

PrinterStartPage

PrinterStopPage

PrintFileCharSepQuote

PrintFileCharSepSeparator

PrintFileLinesPerPage

PrintFileName

PrintFileODBCPassword

PrintFileODBCSource

PrintFileODBCTable

PrintFileODBCUser

PrintFileType

PrintFileUseRptDateFmt

PrintFileUseRptNumberFmt

PrintMonth

PrintYear

ProgressDialog

RecordsPrinted

RecordsRead

RecordsSelected

ReportDisplayPage

ReportFileName

ReportLatestPage

ReportSource

ReportStartPage

ReportTitle

SectionFont

SectionFormat

SectionLineHeight

SectionMinHeight

SelectionFormula

SessionHandle

SortFields

SQLQuery

Status

StoredProcParam

SubreportToChange

UserName

WindowAllowDrillDown

WindowBorderStyle

WindowControlBox

WindowControls

WindowHeight

WindowLeft

WindowMaxButton

WindowMinButton

WindowParentHandle

WindowShowCancelBtn

WindowShowCloseBtn

WindowShowExportBtn

WindowShowGroupTree

WindowShowNavigationCtls

WindowShowPrintBtn

WindowShowPrintSetupBtn

WindowShowProgressCtls

WindowShowRefreshBtn

WindowShowSearchBtn

WindowShowZoomCtl

WindowTitle

WindowTop

WindowWidth


Action

Action specifies the trigger for the printing of the report.

Syntax

[form.]Report.Action = 1

For example:

CrystalReport1.Action = 1

«Prints the specified report.»

Remarks

Set the Action property to 1 in your procedure code (CrystalReport1.Action = 1) to print the report in response to a user event.

Data Type

Integer

Availability

Runtime

Related Report Engine Functions

PEStartPrintJob


BoundReportFooter

BoundReportFooter indicates whether or not a footer is printed at the bottom of each page with a page number when printing a bound report.

Syntax

[form.]Report.BoundReportFooter[= {True|False}]

For example:

CrystalReport1.BoundReportFooter = True

«Displays a footer at the bottom of each page of the bound report with a page number.»

Remarks
  • This property is ignored if the ReportSource, is set to 0.
  • The default value for this property is False.
  • This property/method is available for subreports.
Data Type

Boolean

Availability

Design Time; Runtime


BoundReportHeading

BoundReportHeading indicates whether or not a report title is displayed in the Page Header section at the top of each page of a bound report.

Syntax

[form.]Report.BoundReportHeading[= Title$]

For example:

CrystalReport1.BoundReportHeading = "Box Office Report"

«Specifies that the title "Box Office Report" be printed at the top of each page of the report.»

Remarks
  • This property is ignored if the ReportSource, is set to 0.
  • If this property is left blank, no report title will be printed.
Data Type

String

Availability

Design Time; Runtime


Connect

Connect specifies the information required to log on to an SQL server or an ODBC data source.

Syntax
[form.]Report.Connect[=
DataSourceName;UserID;Password;DatabaseQualifier$]

For example:

CrystalReport1.Connect = "DSN = Accounting;UID = 734;PWD = bigboard;DSQ
= Administration"

«Connects to the "Administration" database on the "Accounting" server using the user ID #734 and the password "bigboard".»
CrystalReport1.Connect = "dsn=; uid=; pwd=bigboard; dsq="

«Connects to a password-protected Paradox database. All that is being passed is the password "bigboard".»
Remarks
  • Use the Connect property when the report connects to only a single ODBC data source or SQL server, and only a single set of log on information is required. If the report connects to multiple data sources that require different log on information, use LogOnInfo.
  • Enter the parameters necessary to log on to the SQL server that you need to be activated for your report. Parameters should be in the following format:

DSN = name;UID = userID;PWD = password;DSQ = database qualifier

    • name is the server name or ODBC data source name,
    • userID is the name you have been assigned for logging on to the SQL server,
    • password is the password you have been assigned for logging on to the SQL server, and
    • database qualifier is the database name if your server uses the database concept.
  • The database qualifier parameter, DSQ, is required only when it is applicable to the ODBC/SQL driver you are using. If your DBMS does not use the database concept, you do not need to specify the DSQ parameter.
  • Before you can use this property for an ODBC/SQL database, you must install the ODBC/SQL driver for whatever SQL database you are planning to use, and put the Database/BIN location in your path.
  • If you are connecting to an SQL or other password protected database directly, without going through ODBC, use the name of the SQL server for the DSN parameter.
Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PESetNthTableLogOnInfo


CopiesToPrinter

CopiesToPrinter specifies the number of copies to be printed if you are printing to a printer. Destination, will specify that the job be sent to a printer rather than a window, etc.

Syntax

[form.]Report.CopiesToPrinter[= NumCopies%]

For example:

CrystalReport1.CopiesToPrinter = 3

«Prints three copies of the specified report.»

Remarks
  • The number you enter must not be a zero or a negative value.
  • This property/method is available for subreports.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PEOutputToPrinter


DataFiles

DataFiles specifies the location of the database files or tables used in the report.

Syntax

[form.]Report.DataFiles(ArrayIndex)[= Location$]

  • Enter the file name and path of each database file or table in your report for which you want to change the location.
  • Use a separate line of code for each file for which you want to change the location.
  • The order of files in the array must conform to the order of files in the report. (You can use the Database|Set Location command to determine the order of files in the report.)
  • The first file in the report is array index (0), the second file is (1), etc.

For example, to change the location of the first and third files in a report (first.dbf and third.dbf) to the c:\new directory, use the following syntax:

CrystalReport1.DataFiles(0) = "c:\new\first.dbf"

CrystalReport1.DataFiles(2) = "c:\new\third.dbf"
Remarks
  • DataFiles is an array property that is available at runtime only.
  • Use this property if you want to run the report with files in different locations than specified in the report.
  • When using this property, you do not have to change the locations of all files in the report. Just make certain that the array index for each file you do change matches the position of that file in the report.
  • This property is cleared once the print job is printed. If you print a second time, the program reverts to the locations as originally specified in the report.
Data Type

Array of strings

Availability

Runtime

Related Report Engine Functions

PESetNthTableLocation


DataSource

DataSource specifies the Data Control from which the bound report will retrieve the data.

Remarks
  • This property is ignored if the ReportSource, is set to 0.
  • The Data Control must exist on the form before this property can be set.
  • This property is only available at design time.
  • This property/method is available for subreports.
Data Type

Data Control object

Availability

Design Time


Destination

Destination specifies the destination to which your report is to be printed (Window, Printer, File or Mail).

Syntax

[form.]Report.Destination[= Destination%]

For example:

CrystalReport1.Destination = 0

«Sends the specified report to print to a window.»

Remarks

Select one of the following print destinations:

  • 0 = Window (Sends the report to a preview window.)
  • 1 = Printer (Sends the report to a printer.)
  • 2 = File (Prints the report to a disk file for printing at a later time or for importing into other applications. If you select this property, you will also have to set thePrintFileName, and the PrintFileType.)
  • 3 = E-mail via MAPI (Sends the report to another person on your network via MAPI e-mail (Microsoft Mail). The report is attached to the e-mail letter in the format specified by the PrintFileType.)
  • 4 = E-mail via VIM (Sends the report to another person on your network via VIM e-mail (cc:Mail). The report is attached to the e-mail letter in the format specified by the PrintFileType.)
  • 5 = To Notes (Sends the report to a Lotus Notes destination.)
  • 6 = To Exchange Folder (Sends the report to a Microsoft Exchange folder).

This property/method is available for subreports.

Data Type

Integer (Enumerated)

Availability

Design Time; Runtime

Related Report Engine Functions

PEOutputToPrinter

PEOutputToWindow

PEExportTo


DetailCopies

DetailCopies specifies the number of copies of each record in the Details section that the program is to print.

Syntax

[form.]Report.DetailCopies[= NumCopies%]

For example:

CrystalReport1.DetailCopies = 3

«Specifies that three (3) copies of each record in the details section are to be printed.»

Remarks
  • If DetailCopies is set to a value less than or equal to zero, the value is ignored and 1 copy of the Detail section of the report is printed.
  • This property/method is available for subreports.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PESetNDetailCopies


DialogParentHandle

DialogParentHandle specifies the handle of the parent window. The program uses this handle to determine the window within which it centers any dialog boxes that it displays (progress dialog boxes, parameter field prompt dialog boxes, etc.).

Syntax

[form.]Report.DialogParentHandle = [HWND]

For example:

CrystalReport1.DialogParentHandle = ParentHwnd

«Specifies the handle of the parent for all dialog boxes that the control will display.»

Remarks
  • Does not affect the placement of the preview window. Preview window placement is determined by the WindowLeft, WindowTop, WindowHeight, and WindowWidth properties.
  • This property/method is available for subreports.
Data Type

Long Integer

Availability

Runtime only

Related Report Engine Functions

PESetDialogParentWindow


DiscardSavedData

DiscardSavedData indicates whether or not the data that is saved with a report should be discarded.

Syntax

[form.]Report.DiscardSavedData[= TrueFalse%]

For example:

CrystalReport1.DiscardSavedData = 1

«Discards the data saved with the specified report.»

Remarks

For TrueFalse% use one of the following values:

  • Do not discard the data: False = 0
  • Discard the data: True = 1

This property/method is available for subreports.

Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PEDiscardSavedData


EMailCCList

EMailCCList specifies the "CC" list to which you want your e-mail message sent.

Syntax

[form.]Report.EMailCCList [= CCList$]

For example:

CrystalReport1.EMailCCList = "John Brown; Jane Doe"

«Sends a CC of the e-mail message to both John Brown and Jane Doe.»

Remarks
  • Applies to both VIM and MAPI.
  • Multiple names must be separated by a semicolon.
  • This property/method is available for subreports.
Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PEExportTo

PEGetExportOptions


EMailMessage

EMailMessage specifies the string that you want to appear as the body of your e-mail message.

Syntax

[form.]Report.EMailMessage[=Message$]

For example:

CrystalReport1.EMailMessage = "The meeting is at 4:00"

«Sets "The meeting is at 4:00" as the body of the e-mail message.»

Remarks
  • Applies to both MAPI and VIM.
  • This property/method is available for subreports.
Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PEExportTo


EMailSubject

EMailSubject specifies the subject line in your e-mail message.

Syntax

[form.]Report.EMailSubject[= Subject$]

For example:

CrystalReport1.EMailSubject = "Staff meeting"

«Sets "Staff meeting" as the subject line in an e-mail message.»

Remarks
  • Applies to both MAPI and VIM.
  • This property/method is available for subreports.
Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PEExportTo


EMailToList

EMailToList specifies the "To" list to which you want your e-mail message sent.

Syntax

[form.]Report.EMailToList [=ToList$]

For example:

CrystalReport1.EMailToList = "Jane Doe"

«Makes Jane Doe the only name in the To list.»

Remarks
  • Applies to both MAPI and VIM.
  • Multiple names must be separated by a semicolon.
  • This property/method is available for subreports.
Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PEExportTo


EMailVIMBCCList

EMailVIMBCCList specifies the "Blind CC" list to which you want your e-mail message sent.

Syntax

[form.]Report.EMailVIMBCCList [=BCCList$]

For example:

CrystalReport1.EMailVIMBCCList = "John Jacobs; Jane Doe"

«Makes John Jacobs and Jane Doe the names for the BCC list.»

Remarks
  • Applies to VIM only, not MAPI.
  • Multiple names must be separated by a semicolon.
  • This property is not available in the 32-bit ActiveX control.
  • This property/method is available for subreports.
Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PEExportTo


ExchangeFolder

ExchangeFolder specifies the Exchange path to which a file will be exported, when you want to export to Microsoft Exchange.

Syntax

[form.]Report.ExchangeFolder [= ExchangeFolderPath$]

For example:

CrystalReport1.ExchangeFolder = "c:\Microsoft\Exchange\newrpt.rpt"

«Send the report to file "newrpt.rpt" in the subdirectory \Microsoft\Exchange.»

Note: ExchangeFolder is case-sensitive. If you enter a value in the wrong case you will receive an error message.

Data Type

String

Availability

Runtime

Remarks

This property/method is available for subreports.

Related Report Engine Functions

PEExportTo


ExchangePassword

Specifies the Exchange password when you want to export to Microsoft Exchange.

Syntax

[form.]Report.ExchangePassword [= Password$]

For example:

CrystalReport1.ExchangePassword = "pickle"

«The Exchange password is "pickle".»

Data Type

String

Availability

Runtime

Remarks

This property/method is available for subreports.

Related Report Engine Functions

PEExportTo


ExchangeProfile

ExchangeProfile specifies the Exchange Profile when you want to export to Microsoft Exchange.

Syntax

[form.]Report.ExchangeProfile [= Profile$]

For example:

CrystalReport1.ExchangeProfile = "James Andrews"

«Specifies "James Andrews" as the Exchange Profile.»

Remarks
  • Usually your profile is your name.
  • This property/method is available for subreports.
Data Type

String

Availability

Runtime

Related Report Engine Functions

PEExportTo


Formulas

Formulas specifies a new string for an existing formula.

Syntax

[form.]Report.Formulas(ArrayIndex)[= "FormulaName= FormulaText"]

Enter the formula name and the string that you want to replace the existing string for each formula that you want to change in your report.

For example, to change a formula @COMMISSION to {file.SALES}*.1, and a second formula @TOTAL to {file.SALES} + {file.COMMISSION}, enter the following:

CrystalReport1.Formulas(0) = "COMMISSION= {file.SALES} *.1"
CrystalReport1.Formulas(1) = "TOTAL= {file.SALES} + {file.COMMISSION}"
Remarks
  • Formulas is an array property that is available at runtime only.
  • Use a separate line of code for each formula you want to change.
  • Change only those formulas that you want to change.
  • The first formula you change must be assigned array index (0), the second must be assigned array index (1), etc.
  • The new formula string must conform to Crystal Reports syntax requirements.
  • This property is cleared once the print job is printed. If you print a second time, the program reverts to the formulas as originally specified in the report.

Note:

  • Spaces are significant in formula names. For this reason, the equals sign must follow the formula name with no intervening spaces.
  • The @ sign is not used when designating a formula name in this property.
  • You can't use this property to create new formulas. You can only use it to change existing formulas.
Data Type

Array of strings

Availability

Runtime

Related Report Engine Functions

PESetFormula


GraphData

GraphData specifies the data used for a specified chart.

Syntax
[form.]Report.GraphData(ArrayIndex%)

[= sectionCode; graphNum; row; col;

field;direction$]

For example:

CrystalReport1.GraphData(0)= "GROUPHDR.0.0; 1; GROUP2; GROUP1; 0; COLANDROW"

«The value in Group 1 is used for the rows of the graph, the value in Group 2 is used for the columns of the graph, the first summarized field added to the report is used to set the value of the risers of the graph, and values in both columns and rows are used to create the graph.»

Remarks

With GraphData, you can specify changes to one or more graphs at runtime. Those changes then take place sequentially when you make the "Action=1" call.

The array index value for GraphData simply specifies the sequence number for the change. Thus:

CrystalReport1.GraphData(0) = "GROUPHDR.0.0; 3; Group1; Group2; 666; COLANDROW"

when making changes to one graph only, but

CrystalReport1.GraphData(0) = "HEADER; 3; Group1; Group2; 666;
COLANDROW" CrystalReport1.GraphData(1) = "GROUPHDR.0.0; 3; Group1;
Group2; 666; COLANDROW"

when making changes to more than one graph.

Use the following table as a guide in supplying the required values for this property:

Parameter | Description | Expected value
sectionCode | Specifies the section in which you want to modify a graph. | Please refer to Overview of Section Codes.
graphNum | The number of the graph within the section you want to modify. | Graphs in a section are numbered, starting with zero, left to right first, then top to bottom.
row | The Group number in the report used to create rows in the graph. | GROUP1, GROUP2, GROUP3,..., GROUP9
col | The Group number in the report used to create columns in the graph. | GROUP1, GROUP2, GROUP3,..., GROUP9
field | The summarization field containing values to be used as the value of each riser in the graph. | The first summary field added to a report is numbered 0, the second is numbered 1, etc.
direction | Whether the values in the rows, the columns, or both are used to create the graph. | ROWS, COLS, ROWANDCOL, or COLANDROW

Data Type

Array of strings

Availability

Runtime


GraphOptions

GraphOptions specifies several of the options for the specified chart.

Syntax
[form.]Report.GraphOptions(ArrayIndex%) [= sectionCode; graphNum;
fontFace; barDirection; labelRisers; gridLines; legend; max; min$]

For example:

CrystalReport1.GraphOptions(0) = "FOOTER;0;Arial;H;T;F;X;max;min"

«Sets the font to Arial, sets horizontal bars, shows a data value on every riser (labelRisers = T), and toggles the grid lines off in the first Graph in the Page Footer section.»

Remarks

With GraphOptions, you can specify changes to one or more graphs at runtime. Those changes then take place sequentially when you make the "Action=1" call. The array index value for GraphOptions simply specifies the sequence number for the change.

Thus:

CrystalReport1.GraphOptions(0) = "GROUPHDR.0.0; 1; Arial; (H; T; F; legend; max; min"

when making changes to one graph only, but

CrystalReport1.GraphOptions(0) = "TITLE; 1 Arial; H; T; F; X; 100; 0"
CrystalReport1.GraphOptions(1) = "TITLE; 1 Arial; H; T; F; X; 100; 0"

when making changes to more than one graph.

Use the following chart as a guide in entering the required property values:

Parameter | Description | Values expected
sectionCode | Specifies the section in which you want to modify a graph. | Please refer to Overview of Section Codes.
graphNum | Specifies which graph in the section you want to modify. | Graphs in a section are numbered, starting with zero, left to right first, then top to bottom.
fontFace | Specifies the font face you want to use for the entire graph. | Actual name of font (i.e., Arial).
barDirection | In a bar graph, specifies the direction in which you want the graph bars to appear. | H = horizontal, V = vertical, X = as is
labelRisers | Specifies whether or not you want to show the data value on every riser. | T= true, F = False, X = as is
gridLines | Specifies whether or not you want to show grid lines. | T= true, F = False, X = as is
legend | Specifies whether or not you want to show a legend. | T= true, F = False, X = as is
max | Specifies the maximum value you want included in your graph. | Enter a number.
min | Specifies the minimum value you want included in your graph. | Enter a number.

Data Type

Array of strings

Availability

Runtime


GraphText

GraphText specifies the various text components for the specified chart.

Syntax
[form.]Report.GraphText(ArrayIndex%)[= sectionCode; graphNum;title;
subTitle; footnote;series;group;x;y;z$]

For example:

CrystalReport1.GraphText(0) = "HEADER; 0;;;;;;new x label; new y
label;new z label"

«Resets the x, y, and z labels for the first graph in the Page Header section.»
Remarks
  • Select your section code from the section code table (see Overview of Section Codes).
  • With GraphText, you can specify changes to one or more graphs at runtime. Those changes then take place sequentially when you make the "Action=1" call. The array index value for GraphText simply specifies the sequence number for the change. Thus:
CrystalReport1.GraphText(0) = " GROUPHDR.0.0; 1; title string;

subtitle string; footnote string; series string; group string;

x string;y string; z string"

when making changes to one graph only, but

CrystalReport1.GraphText(0) = "TITLE; 1; title string; subtitle

string; footnote string; series string; group string; x string;

y string; z string"
CrystalReport1.GraphText(1) = "TITLE; 1; title string; subtitle

string; footnote string; series string; group string; x string;

y string; z string"

when making changes to more than one graph.

  • title, subTitle, footnote, series, group, x, y, and z are the strings you want to label the appropriate parts of the graph.
Data Type

Array of strings

Availability

Runtime


GraphType

GraphType specifies the kind of chart used in the selected section in the specified report.

Syntax

[form.]Report.GraphType(ArrayIndex%)[=sectionCode;graphNum;graphType$]

For example:

CrystalReport1.GraphType(0)= "GROUPHDR.0.0; 0; PIE"

«Specifies a Pie graph as the first graph (graphNum =0) in the Group Header 1 section.»

Remarks
  • With GraphType, you can specify changes to one or more graphs at runtime. Those changes then take place sequentially when you make the "Action=1" call.

    The array index value for GraphType specifies the sequence number for the change. Thus:

    CrystalReport1.GraphType(0) = "GROUPHDR.0.0; 0; PIE"

when making changes to one graph only, but

    CrystalReport1.GraphType(0) = "HEADER; 0; PIE"

    CrystalReport1.GraphType(1) = "GROUPHDR.0.0; 0; PIE"

     when making changes to more than one graph.
  • Select sectionCode from the section code table, see Overview of Section Codes.
  • Graph numbers are 0 origin; the first graph in a section is number 0, the second is number 1, etc.
  • Multiple graphs in a section are numbered left to right first, then top to bottom.
  • Select from the following graph types for the GraphType value for this property:

    For this type of graph Use this code for graphType

    Side-by-side

    SIDEBYSIDE

    3-D side-by-side

    3DSIDE

    Stacked bar

    STACKEDBAR

    3-D stacked bar

    3DSTACKED

    Percent bar

    PERCENTBAR

    3-D percent bar

    3DPERCENT

    Line

    LINE

    Area

    AREA

    3-D bars

    3DBARS

    Pie

    PIE

    Multiple pie

    MULTIPLEPIE

    Weighted pie

    WEIGHTEDPIE

Data Type

Arrays of strings

Availability

Runtime


GroupCondition

GroupCondition specifies what kind of change in the Group Condition Field will trigger the creation of a group.

Syntax
[form.]Report.GroupCondition(SequentialIndex%)

[= group; field; condition; sortDirection$]

For example:

CrystalReport1.GroupCondition(0) = "GROUP1;{order details.ORDER
ID};ANYCHANGE;A"

«Specifies that any change in the ordernum field in Group1 will trigger a new grouping.»
Remarks

Refer to the following tables for parameter values for this property:

Parameter | Description | Values expected
group | The group in which you want to set the group condition. | The outermost group on the report is GROUP1, the next group is GROUP2, etc.
field | The name of the field that triggers a grouping whenever its value changes. | Enter the name in the following format: {table.FIELDNAME}
condition | Enter the condition that triggers the grouping. | See the tables below.
sortDirection | The direction in which groups are to be sorted. | A = Ascending, D = Descending.
 | Condition (Date Fields) | Condition Code
 | Daily | DAILY
 | Weekly | WEEKLY
 | Bi-weekly | BIWEEKLY
 | Semi-monthly | SEMIMONTHLY
 | Monthly | MONTHLY
 | Quarterly | QUARTERLY
 | Semi-annually | SEMIANNUALLY
 | Annually | ANNUALLY
 | Condition (Boolean Fields) | Condition Code
 | To Yes | TOYES
 | To No | TONO
 | Every Yes | EVERYYES
 | Every No | EVERYNO
 | Next Is Yes | NEXTISYES
 | Next Is No | NEXTISNO
 | Condition for all other data types
 | Any Change | ANYCHANGE

Data Type

Array of strings

Availability

Runtime only

Related Report Engine Functions

PESetGroupCondition


GroupSelectionFormula

GroupSelectionFormula specifies the groups to be used when printing the report.

Syntax
[form.]Report.GroupSelectionFormula

[= "GroupSelectionFormula"]

Enter the group selection formula just as you would enter it in the Formula Editor. For example, to limit your report to those groups with a subtotal on the {order details.ORDER AMOUNT} field less than $10,000 (with subtotals triggered by changes in the {customer.CUSTOMER ID field}, you would enter the following as a group selection formula:

Sum ({order details.ORDER AMOUNT}, {customer.CUSTOMER ID}) < $10000

Remarks

If your group selection formula includes internal quotes, change all of the internal double quotes to single quotes and then surround the entire selection formula in double quotes.

Note: If you have created a group selection formula in your report at Design Time, any group selection formula you enter here will be appended to that group selection formula, connected by an "and". Thus, your records will be selected based on a combination of the two formulas.

Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PESetGroupSelectionFormula


GroupSortFields

GroupSortFields specifies the group field(s) that are to be used to sort your data when the report is printed.

Syntax
[form.]Report.GroupSortFields(ArrayIndex)

[= "+|-GroupField"]

Enter the group field(s) on which you want your report to be sorted.

For example, assume that you have broken your data into state groups and had Crystal Reports count the number of customers in each group. In order to print the group with the highest count first, then the group with the next highest count, etc. (descending order), enter a string similar to the following:

CrystalReport1.GroupSortFields(0) = "-Count

({customer.CUSTOMER ID},{customer.REGION})"
Remarks
  • GroupSortFields is an array property available at runtime only.
  • Use a separate line of code to specify each group sort field.
  • Enter group sort fields in the order that you want them to sort your report. For example, if you want your report to be sorted first on group sort field A and then on group sort field B, specify group sort field A in your first line of code and group sort field B in your second line of code.
  • The first group sort field you specify must be assigned array index 0, the second group sort field must be assigned array index 1, etc.
  • The index values you assign must be continuous; no gaps are allowed (0, 1, 2 = OK, 0, 1, 3 = wrong).
  • Array index values must be subscripted in the code immediately after the property name (i.e., CrystalReport1.GroupSortFields(0) =).
  • If you have specified sort fields for your report at Design Time, any sort fields you enter here will replace the sort fields in your report.
  • If you do not use this property, the program will use the sorting instructions that you specified in the report.
  • If you want to clear the group sort fields in your report, use an empty string (i.e., CrystalReport1.GroupSortFields(0) = "").
  • This property is cleared once the print job is printed. If you print a second time, the program reverts to the group sort fields as originally specified in the report.

Note:

  • The group sort field entry must follow the sort direction sign (+ or -) with no intervening space.
  • To find the correct syntax for any group in your report using Crystal Reports for Visual Basic:
      • choose the Formula Field command from the Insert menu,
      • enter any formula name in the Insert Formula dialog box when it appears,
      • click the scroll button on the Fields list in the Formula Editor when it appears, and
      • double-click the group field of interest.
  • Crystal Reports enters the group field name in the Formula text box. Use the name and syntax from that text box when constructing your group sort field string.
Data Type

Array of strings

Availability

Runtime

Related Report Engine Functions

PESetNthAlertConditionFormula


LastErrorNumber

LastErrorNumber specifies the error code for the last runtime error.

Syntax

[form.]Report.LastErrorNumber

For example:

'If error occurs, go to Error Handler

On Error GoTo ErrorHandler
ErrorHandler:

    MsgBox CrystalReport1.LastErrorNumber

«If an error occurs, this code calls up a message box that displays the error number.»
Remarks
  • LastErrorNumber is a runtime-only property.
  • This property/method is available for subreports.

Note: LastErrorNumber must come after the Action call in order to display relevant values. After you have printed your report, you can refer to this property to get an error number (if any). If there was no error in printing, LastErrorNumber = 0.

Data Type

Integer

Availability

Runtime

Related Report Engine Functions

PEGetErrorCode


LastErrorString

LastErrorString specifies the error string for the last runtime error.

Syntax

[form.]Report.LastErrorString

For example:

'If error occurs, go to Error Handler

On Error GoTo ErrorHandler
ErrorHandler:

    MsgBox CrystalReport1.LastErrorString

«If an error occurs, this code calls up a message box that displays the error string.»
Remarks
  • LastErrorString is a runtime-only property.
  • This property/method is available for subreports.

Note: LastErrorString must come after the Action call in order to display relevant values. After you have printed your report, you can refer to this property to get an error string (if any). If there was no error in printing, LastErrorNumber = 0.

Data Type

String

Availability

Runtime

Related Report Engine Functions

PEGetErrorCode

PEGetErrorText


LogOnInfo

LogOnInfo specifies the information required to log on to one or more SQL servers or password-protected databases.

Syntax
[form.]Report.LogOnInfo(ArrayIndex)[ =
Name;UserID;Password;DatabaseQualifier$]

For example:

CrystalReport1.LogOnInfo[0] = "DSN = Accounting;UID = 734;PWD =
bigboard;DSQ = Administration"

«Connects to the "Administration" database on the "Accounting" server using the user ID #734 and the password "bigboard".»
CrystalReport1.LogOnInfo[0] = dsn=;uid=;pwd=bigboard;dsq=?

«Connects to a password-protected Paradox database. All that is being passed is the password bigboard.»
Remarks
  • Use the LogOnInfo property when the report connects to multiple data sources that require different log on information. If the report connects to only a single ODBC data source or SQL server, and only a single set of log on information is required, simply pass 0 as the array index, or Connect, can be used instead.
  • Use a separate line of code for each table for which you want to change the logon info.
  • The order of tables in the array must conform to the order of tables in the report. (You can use the Database|Set Location command to determine the order of tables in the report.)
  • The first table in the report is array index (0), the second file is (1), etc. For example, to change the logon information of the first and third tables in a report to the NEW server, use the following syntax:
CrystalReport1.LogOnInfo(0) = "DSN = NEW;UID = 734;PWD = bigboard;DSQ =
Administration1"CrystalReport1.LogOnInfo(2) = "DSN = NEW;UID = 734;PWD =
bigboard;DSQ = Administration2"
  • LogOnInfo is an array property that is available at runtime only.
  • Enter the parameters necessary to log on to each SQL server table that you need to change information for in your report. Parameters should be in the following format:

DSN = name;UID = userID;PWD = password;DSQ = database qualifier

    • name is the server name,
    • userID is the name you have been assigned for logging on to the SQL server,
    • password is the password you have been assigned for logging on to the SQL server, and
    • database qualifier is the database name if your server uses the database concept.
  • The database qualifier parameter (DSQ) is required only when it is applicable to the ODBC/SQL driver you are using. If your DBMS does not use the database concept, you do not need to specify the DSQ parameter.
  • Before you can use this property for an ODBC/SQL database, you must install the ODBC/SQL driver for whatever SQL database you are planning to use, and put the Database/BIN location in your path.
  • If you are connecting to an SQL or other password protected database directly, without going through ODBC, use the name of the SQL server for the DSN parameter.
  • RetrieveLogonInfo, can be used to populate this property with log on information automatically.
Data Type

Array of strings

Availability

Runtime


MarginBottom

MarginBottom specifies the bottom margin for the specified report.

Syntax

[form.]Report.MarginBottom[=MarginSetting%]

For example:

CrystalReport1.MarginBottom = 720

«Sets a 1/2 inch bottom margin for the report (1 inch = 1440 twips).»

Remarks

MarginSetting is the margin you want, in twips. A twip is 1/20th of a point. There are 72 points and thus 1440 twips in an inch.

Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PESetMargins


MarginLeft

MarginLeft specifies the left margin for the specified report.

Syntax

[form.]Report.MarginLeft[=MarginSetting%]

For example:

CrystalReport1.MarginLeft = 1440

«Sets a 1 inch left margin for the report (1 inch = 1440 twips).»

Remarks

MarginSetting is the margin you want, in twips.

Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PESetMargins


MarginRight

MarginRight specifies the right margin for the specified report.

Syntax

[form.]Report.MarginRight[=MarginSetting%]

For example:

CrystalReport1.MarginRight=1440

«Sets a 1 inch right margin for the report (1 inch = 1440 twips).»

Remarks

MarginSetting is the margin you want, in twips.

Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PESetMargins


MarginTop

MarginTop specifies the top margin for the specified report.

Syntax

[form.]Report.MarginTop[=MarginSetting%]

For example:

CrystalReport1.MarginTop = 720

«Sets a 1/2 inch top margin for the report (1 inch = 1440 twips).»

Remarks

MarginSetting is the margin you want, in twips.

Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PESetMargins


ParameterFields

ParameterFields specifies the default value of the specified parameter field. When the prompting dialog box appears for the parameter field, the value specified with this property will be the default value that appears. This property is not available for subreports.

Syntax
[form.]Report.ParameterFields(ArrayIndex)[="ParameterName;

NewValue;SetCurrentValue"]
Remarks
  • The parameter, SetCurrentValue can either be set to TRUE or FALSE.
  • If set to TRUE, the parameter value is passed to the current value in the report; the user is not prompted to enter the parameter value.
  • If set to FALSE, the parameter value is passed to the default value for the parameter; the user is prompted to enter the parameter value, with the value you set showing as the default value.
  • The default value for SetCurrentValue is FALSE.
  • This property does not eliminate the prompt by specifying a current value for the parameter field. You will still be prompted but the default value in the prompt will be the value you specify.
  • Use a separate line of code for each parameter field for which you want to change the value.
  • The order of values in the array must conform to the order of parameter fields in the report.
  • The first parameter field in the report is array index (0), the second is (1), etc.
  • For example:
      • To change the value of the first parameter field in a report (parameter1) to "red" use the following syntax (user will not be prompted to enter a value):
        CrystalReport1.ParameterFields(0) = "parameter1;red;TRUE"

    • To change the value in a Date parameter field use the following syntax (user will not be prompted to enter a value):
        CrystalReport1.ParameterFields(0) =
"DatePar;Date(1998,12,7);TRUE"

    • To prompt the user to change the value of the third parameter field in a report (parameter3) use the following syntax (user will be prompted to use the default value set using the NewValue parameter below - "blue"):
        CrystalReport1.ParameterFields(2) = "parameter3;blue;FALSE"
Data Type

Array of strings

Availability

Runtime only

Related Report Engine Functions

PESetNthParameterField


Password

Password specifies the password needed to use database tables on a restricted Access .MDB file.

Syntax

[form.]Report.Password[= Password$]

For example:

CrystalReport1.Password = "dogsncats"

«Enters the password dogsncats.»

Data Type

String

Availability

Runtime

Remarks
  • Enter the password you have been assigned.
  • In Microsoft Access 95 and later, an Access database can have session security (also know as user-level security), database-level security, or both. If the Access database contains only session security, simply pass the session password to the Password property. If the Access database contains database-level security, use a linefeed character, Chr(10), followed by the database-level password. For example:
CrystalReport1.Password = Chr(10) & "dbpassword"

If the Access database contains both session security and database-level security, use the session password followed by the linefeed character and the database password:

CrystalReport1.Password "sesspswd" & Chr(10) & "dbpassword"

Alternately, database-level security can also be handled by assigning the database-level password to the Password parameter of the LogOnInfo, property.

Related Report Engine Functions

PESetNthTableSessionInfo


PrintDay

PrintDay specifies the day component of the print date (if different from the actual date the report is printed).

Syntax

[form.]Report.PrintDay[=Day%]

For example:

CrystalReport1.PrintDay = 23

«Sets 23 as the print day.»

Remarks
  • Enter a value from 1 to 31.
  • PrintYear, PrintMonth, and PrintDay work together to define the date that the report is to be printed. All three properties must be set in order to define a new print date. If all three properties are not set, the date saved with the report is used. This may be the user's default date if none has been specified in the report.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PESetPrintDate


PrinterCollation

PrinterCollation indicates whether or not copies will be collated when printed, if more than one copy is to be printed. Use PrinterCopies, to specify how many copies should be printed.

Syntax

[form.]Report.PrinterCollation[=CollationCode%]

For example:

CrystalReport1.PrinterCollation = 1

«Collates the copies of the specified report.»

Remarks

Select your CollationCode% value from the following table:
Status | Code
Uncollated | 0
Collated | 1
Default Collation | 2

This property/method is not available for subreports.

Data Type

Integer (Enumerated)

Availability

Design Time; Runtime

Related Report Engine Functions

PESetPrintOptions


PrinterCopies

PrinterCopies specifies the number of report copies to be printed. PrinterCollation, indicates whether or not the copies will be collated when printed.

Syntax

[form.]Report.PrinterCopies[=NumCopies%]

For example:

CrystalReport1.PrinterCopies = 3

«Specifies that the program is to print three copies of the report.»

Remarks
  • The number used for PrinterCopies must not be zero or a negative value.
  • This property/method is available for subreports.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PESetPrintOptions


PrinterDriver

PrinterDriver specifies the name of the printer driver that is to be used when the report is printed.

Syntax

[form.]Report.PrinterDriver [= DriverName$]

For example:

CrystalReport1.PrinterDriver = "Epson24.drv"

«Sets the printer driver to be the Epson 24 pin driver.»

Remarks
  • PrinterDriver, PrinterName, and PrinterPort, work together to define the printer that the report is to be sent to. All three properties must be set in order to define a new printer. If all three properties are not set, the printer defined in the report will be used. This may be the user's default printer if none has been specified in the report.
  • This property/method is available for subreports.
  • For an example of how to use this property look in the WIN.INI file under the Devices section. You will find something like this:
[Devices]

HP LaserJet 4/4M=HPPCL5MS,hp4_tech_1
  • The PrinterName is the HP LaserJet 4/4M, left of the = sign
  • The PrinterDriver is the HPPCL5MS, first variable after the = sign
  • The PrinterPort is the hp4_tech_1, the second variable after the = sign. Port is often something like "LPT1:"
Data Type

String

Availability

Design Time; Runtime


PrinterName

PrinterName specifies the name of the printer that is to print the report.

Syntax

[form.]Report.PrinterName[= PrinterName$]

For example:

CrystalReport1.PrinterName = "Epson LQ-850"

«Specifies the Epson LQ-850 printer.»

Remarks
  • PrinterDriver, PrinterName, and PrinterPort, work together to define the printer that the report is to be sent to. All three properties must be set in order to define a new printer. If all three properties are not set, the printer defined in the report will be used. This may be the user's default printer if none has been specified in the report.
  • This property/method is available for subreports.
  • For an example of how to use this property look in the WIN.INI file under the Devices section. You will find something like this:
[Devices]

HP LaserJet 4/4M=HPPCL5MS,hp4_tech_1
  • The PrinterName is the HP LaserJet 4/4M, left of the = sign
  • The PrinterDriver is the HPPCL5MS, first variable after the = sign
  • The PrinterPort is the hp4_tech_1, the second variable after the = sign. Port is often something like "LPT1:"
Data Type

String

Availability

Design Time; Runtime


PrinterPort

PrinterPort specifies the name of the printer port for the specified printer.

Syntax

[form.]Report.PrinterPort[= PortName$]

For example:

CrystalReport1.PrinterPort= "LPT1"

«Sets the printer port to LPT1.»

Remarks
  • PrinterDriver, PrinterName, and PrinterPort work together to define the printer that the report is to be sent to. All three properties must be set in order to define a new printer. If all three properties are not set, the printer defined in the report will be used. This may be the user's default printer if none has been specified in the report.
  • This property/method is available for subreports.
  • For an example of how to use this property look in the WIN.INI file under the Devices section. You will find something like this:
[Devices]

HP LaserJet 4/4M=HPPCL5MS,hp4_tech_1
  • The PrinterName is the HP LaserJet 4/4M, left of the = sign
  • The PrinterDriver is the HPPCL5MS, first variable after the = sign
  • The PrinterPort is the hp4_tech_1, the second variable after the = sign. Port is often something like "LPT1:"
Data Type

String

Availability

Design Time; Runtime


PrinterStartPage

PrinterStartPage specifies the first page to be printed.

Syntax

[form.]Report.PrinterStartPage[= StartPage%]

For example:

CrystalReport1.PrinterStartPage = 7

«Specifies that printing is to begin with Page 7 of the report.»

Remarks
  • If a value less than or equal to 0 is used for PrinterStartPage, the value is ignored and printing starts with Page 1.
  • This property/method is available for subreports.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PESetPrintOptions


PrinterStopPage

PrinterStopPage specifies the last page to be printed.

Syntax

[form.]Report.PrinterStopPage[=StopPage%]

For example:

CrystalReport1.PrinterStopPage = 12

«Specifies that the printing is to end with Page 12 of the report.»

Remarks
  • Use a value of 0 for PrinterStopPage to indicate that printing is to continue through to the last page.
  • This property/method is available for subreports.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PESetPrintOptions


PrintFileCharSepQuote

PrintFileCharSepQuote specifies the quote character used to enclose alphanumeric field data when printing to a file using character-separated format.

Syntax

[form.]Report.PrintFileCharSepQuote[=Quote$]

For example:

CrystalReport1.PrintFileCharSepQuote = "'"

«Uses the quotation character (') to surround values saved in character-separated format.»

Remarks
  • Applies only when PrintFileType, is 5 - Character-separated values.
  • Applies only when Destination, is 2 - File, 3 - E-mail to MAPI, or 4 - E-mail to VIM.
  • If you assign a string to PrintFileCharSepQuote that is longer than one character, only the first character of that string is used. For example, if you assign "quote" to the property, only "q" is recognized.
  • This property/method is available for subreports.
Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PEExportTo


PrintFileCharSepSeparator

PrintFileCharSepSeparator specifies the character(s) you want to use to separate the fields when printing to a file using the Character Separated Value format.

Syntax

[form.]Report.PrintFileCharSepSeparator [=Separator$]

For example:

CrystalReport1.PrintFileCharSepSeparator= "@"

«Specifies that the "@" character is to be used for separating field values.»

Remarks
  • Applies only when PrintFileType, is 5 - Character-separated values.
  • Applies only when Destination, is 2 - File, 3 - E-mail to MAPI, or 4 - E-mail to VIM.
  • This property/method is available for subreports.
Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PEExportTo


PrintFileLinesPerPage

PrintFileLinesPerPage specifies the number of lines to be printed before the page break. The default is 60 lines per page.

Syntax

[form.]Report.PrintFileLinesPerPage

For example:

CrystalReport1.PrintFileLinesPerPage = 50

«Fifty lines will be printed before a page break.»

Data Type

Integer

Availability

Runtime

Remarks

This property/method is available for subreports.


PrintFileName

PrintFileName specifies the name of the file to which the report is to be printed.

Syntax

[form.]Report.PrintFileName[= FileName$]

For example:

CrystalReport1.PrintFileName = "c:\crw\cust_rpt.txt"

«Prints the report to a file named "cust_rpt.txt" in the C:\CRW directory.»

Remarks
  • You can double-click this property or click the ellipsis (...) in the Properties box to call up the Choose Print Filename dialog box. In that dialog box, select the name of the file and the path to which you want the program to print the report.
  • Select a value for this property only if you are printing to a file, if the value you assigned to the Destination, is 2 - File.
  • This property/method is available for subreports.

Note: If you want to specify the PrintFileName at runtime, make certain that you enclose it in quotes in your code.

Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PEExportTo


PrintFileODBCPassword

PrintFileODBCPassword specifies the password that you need to connect to the data source, whenever you want to export in ODBC format.

Syntax

[form.]Report.PrintFileODBCPassword[= Password$]

For example:

CrystalReport1.PrintFileODBCPassword = "merry%%5"

«"merry%%5" is the name of the password to connect to the data source.»

Remarks
  • This is only required if the ODBC datasource that you are exporting to requires a password.
  • This property/method is available for subreports.
Data Type

String

Availability

Design Time; Runtime


PrintFileODBCSource

PrintFileODBCSource specifies the name of the data source to which you want to export, whenever you export in ODBC format.

Syntax

[form.]Report.PrintFileODBCSource[= DataSource$]

For example:

CrystalReport1.PrintFileODBCSource = "pickle"

«"pickle" is the name of the data source that you want to export to.»

Data Type

String

Availability

Design Time; Runtime

Remarks

This property/method is available for subreports.


PrintFileODBCTable

PrintFileODBCTable specifies the name of the table in the data source to which you want to export, whenever you want to export in ODBC format.

Syntax

[form.]Report.PrintFileODBCTable[= TableName$]

For example:

CrystalReport1.PrintFileODBCTable = "Employees"

«"Employees" is the name of the table in the data source to export to.»

Data Type

String

Availability

Design Time; Runtime

Remarks

This property/method is available for subreports.


PrintFileODBCUser

PrintFileODBCUser specifies the User ID that you need to connect to the data source, whenever you export in ODBC format.

Syntax

[form.]Report.PrintFileODBCUser[= UserID$]

For example:

CrystalReport1.PrintFileODBCUser = "LisaB"

«"LisaB" is the User ID needed to connect to the data source.»

Data Type

String

Availability

Design Time; Runtime

Remarks

This property/method is available for subreports.


PrintFileType

PrintFileType specifies the type of print file to use when printing a report to a file.

Syntax

[form.]Report.PrintFileType[= FileType%]

For example:

CrystalReport1.PrintFileType = 1

«Prints the report to a file in a tab separated format.»

Remarks

Select one of the following print file types if you are printing to a file, if the value you assigned to the Destination, is 2 - File.

0 - Record

Record style (columns of values). Does not use commas or separators. Outputs every record with a fixed field width.

1 - Tab separated

Tab separated values. Presents data in tabular form. Encloses alphanumeric field data in quotes and separates fields with tabs.

2 - Text

Text style. Saves the data in ASCII text format with all values separated by spaces. This style looks most like the printed page.

3 - DIF

Saves the data in DIF (data interchange format) format. This format is often used for the transfer of data between different spreadsheet programs.

4 - CSV

Comma separated values. Encloses alphanumeric field data in quotes and separates fields with commas.

5 - Character Separated

Saves the data as character separated values in ASCII text format. All values are separated by a character or characters specified by the PrintFileCharSepSeparator.

6 - Tab separated text

Saves the data in ASCII text format with all values separated by tabs.

7 - Crystal Reports (RPT)

Standard Crystal Reports (RPT) format is used. Most often used for sending the report to another user via e-mail.

8 - Excel 2.1 XLS

Exports the report as a Microsoft Excel 2.1 worksheet.

9 - Excel 3.0 XLS

Exports the report as a Microsoft Excel 3.0 worksheet.

10 - Excel 4.0 XLS

Exports the report as a Microsoft Excel 4.0 worksheet.

11 - Lotus 1-2-3 WK1

Exports the report as a Lotus 1-2-3 WK1 format worksheet.

12 - Lotus 1-2-3 WK3

Exports the report as a Lotus 1-2-3 WK3 format worksheet.

13 - Lotus 1-2-3 WKS

Exports the report as a Lotus 1-2-3 WKS format worksheet.

14 - Quattro Pro 5.0 WB1 (16-bit only)

Exports the report as a Quattro Pro 5.0 WB1 format file.

15 - RTF

Saves the data in Rich Text Format.

16 - Word for DOS (16-bit only)

Uses the Microsoft Word for DOS format to save the data in the report.

17 - Word for Windows

Uses the Microsoft Word for Windows format to save the data in the report.

18 - WordPerfect (16-bit only)

Uses WordPerfect format to save the data in the report.

19 - Excel 5

Uses Excel 5 format to save the data in the report.

20 - HTML 3

Uses HTML 3 format to save the data in the report.

21 - HTML Internet Explorer

Uses the Internet Explorer version of HTML to save the data in the report.

22 - HTML Netscape

Uses the Netscape version of HTML to save the data in the report.

23 - HTML Netscape

Saves the data in ASCII text format, broken into pages.

24 - ODBC

Exports to a database format corresponding with an ODBC data source that you specify.

Note: If you specify a table name for PrintFileODBCTable that already exists in the database, you will receive an error stating that the table already exists.

25 - Paginated Text

Text style. Saves the data in ASCII text format with pagination information.

This property/method is available for subreports.

Data Type

Integer (Enumerated)

Availability

Design Time; Runtime

Related Report Engine Functions

PEExportTo


PrintFileUseRptDateFmt

PrintFileUseRptDateFmt specifies, when printing to a file, whether or not the program should save dates in the same date format (MDY, DMY, etc.) that is used in the report or instead optimize the dates for the file format you have selected.

Syntax

[form.]Report.PrintFileUseRptDateFmt[= TrueFalse%]

For example:

CrystalReport1.PrintFileUseRptDateFmt = 1

«Specifies that the program should print dates in the same format as used in the report.»

Remarks
  • Applies only when PrintFileType, is 0 - Record, 1 - Tab-separated, 3 - Data Interchange Format (DIF), 4 - CSV, or 5 - Character-Separated.
  • Applies only when Destination, is 2 - File, 3 - E-mail to MAPI, or 4 - E-mail to VIM.
  • For TrueFalse%, use one of the following values:
      • False = 0
      • True = 1
  • This property/method is available for subreports.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PEExportTo


PrintFileUseRptNumberFmt

PrintFileUseRptNumberFmt specifies, when printing to a file, whether or not the program should print numbers in the same format (decimal places, negatives, etc.) that you have used in the report or instead, optimize the numbers for the file format you have selected.

Syntax

[form.]Report.PrintFileUseRptNumberFmt [=TrueFalse%]

For example:

CrystalReport1.PrintFileUseRptNumberFmt = 1

«Specifies that the program should print numbers in the same format as used in the report.»

Remarks
  • Applies only when PrintFileType, is 0 - Record, 1 - Tab-separated, 3 - Data Interchange Format (DIF), 4 - CSV, or 5 - Character-Separated.
  • Applies only when Destination, is 2 - File, 3 - E-mail to MAPI, or 4 - E-mail to VIM.
  • For TrueFalse%, use one of the following values:
      • False = 0
      • True = 1
  • This property/method is available for subreports.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PEExportTo


PrintMonth

PrintMonth specifies the month component of the print date (if different from the actual date the report is printed).

Syntax

[form.]Report.PrintMonth[= Month%]

For example:

CrystalReport1.PrintMonth= 7

«Sets July as the print month.»

Remarks
  • Enter a value from 1-12 where January = 1, and December = 12.
  • PrintYear, PrintMonth, and PrintDay, work together to define the date that the report is to be printed. All three properties must be set in order to define a new print date. If all three properties are not set, the date saved with the report is used. This may be the user's default date if none has been specified in the report.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PESetPrintDate


PrintYear

PrintYear specifies the year component of the print date (if different from the actual date the report is printed).

Syntax

[form.]Report.PrintYear[=Year%]

For example:

CrystalReport1.PrintYear = 1994

«Sets the year component of the print date to 1994.»

Remarks
  • Enter the print year as a four-digit number.
  • PrintYear, PrintMonth, and PrintDay, function together. You must change the value of all three to change the print date. If you do not change all three, the print date saved with the report is used. This may be the current date if a specific date is not saved with the report.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PESetPrintDate


ProgressDialog

ProgressDialog indicates whether the display of the Progress dialog box is enabled or disabled. The Progress dialog box displays the progress of the report when it is running (records read, records selected, and so forth).

Syntax

[form.]Report.ProgressDialog[= {True|False}]

For example:

CrystalReport1.ProgressDialog = False

«Turns off the Progress dialog box that usually appears during exporting or printing.»

Remarks
  • Use this property to indicate whether or not a progress dialog box should be displayed while the report is printed or exported. This property is set to True by default.
  • This property/method is available for subreports.
Data Type

Boolean

Availability

Design Time; Runtime

Related Report Engine Functions

PEEnableProgressDialog


RecordsPrinted

RecordsPrinted specifies the number of records actually printed.

Syntax

[form.]Report.RecordsPrinted

For example:

Printed& = CrystalReport1.RecordsPrinted

«Fetches the number of records printed and stores it in the Printed variable.»

Remarks
  • If the report being printed contains one or more group selection formulas, the value returned by RecordsPrinted may be significantly less than the value returned by RecordsSelected. Otherwise, this value should equal RecordsSelected.
  • This property/method is available for subreports.
Data Type

Long

Availability

Runtime

Related Report Engine Functions

PEGetJobStatus


RecordsRead

RecordsRead specifies the number of records actually processed.

Syntax

[form.]Report.RecordsRead

For example:

Read% = CrystalReport1.RecordsRead

«Fetches the number of records read and saves it in the Read variable.»

Remarks
  • If the Crystal Report Engine generates a SQL query to obtain data from a SQL database when the report is printed, RecordsRead will only return the number of records received by the Crystal Report Engine from the query. This value may be significantly smaller than the number of records actually in the SQL database table.
  • This property/method is available for subreports.
Data Type

Long

Availability

Runtime

Related Report Engine Functions

PEGetJobStatus


RecordsSelected

RecordsSelected specifies the number of records selected for inclusion in the report out of the total number of records read.

Syntax

[form.]Report.RecordsSelected

For example:

Selected& = CrystalReport1.RecordsSelected

«Fetches the number of records selected and saves it in the Selected variable.»

Remarks
  • RecordsSelected will return a value anywhere between zero and the value returned by RecordsRead. The value returned by RecordsSelected depends on the queries and selection formulas set up in the report.
  • This property/method is available for subreports.
Data Type

Long

Availability

Runtime

Related Report Engine Functions

PEGetJobStatus


ReportDisplayPage

ReportDisplayPage indicates which page of a multi-page report is currently being displayed in the preview window.

Syntax

[form.]Report.ReportDisplayPage

For example:

Result% = CrystalReport1.ReportDisplayPage

«Fetches the number of the displayed page and stores it in the Result variable.»

Data Type

Integer

Availability

Runtime

Remarks

This property/method is available for subreports.

Related Report Engine Functions

PEGetJobStatus


ReportFileName

ReportFileName specifies the name of the report to be printed.

Syntax

[form.]Report.ReportFileName[= ReportName$]

For example:

CrystalReport1.ReportFileName = "c:\crw\company.rpt"

«Prints the report named "company.rpt" that is located in the C:\CRW directory.»

Remarks
  • You can double-click this property or click the ellipsis (...) in the Properties box to call up the Choose Report File dialog box. In that dialog box, select the name and path of the report you want the program to print in response to a Crystal ActiveX Control event.
  • This property/method is available for subreports.

Note: If you want to specify the ReportFileName at runtime, make certain that you enclose it in quotes in your code.

Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PEOpenPrintJob


ReportLatestPage

ReportLatestPage specifies the last page printed in the specified report.

Note: ReportLatestPage will only contain the last page number after calling CrystalReport1.PageCount.

Syntax

[form.]Report.ReportLatestPage

For example:

Latest% = CrystalReport1.ReportLatestPage

«Fetches the number of the last page printed and stores it in the Latest variable.»

Data Type

Integer

Availability

Runtime

Remarks

This property/method is available for subreports.

Related Report Engine Functions

PEGetJobStatus


ReportSource

ReportSource specifies the source of the report as a report file, a Visual Basic data control, or a True Grid data control.

Syntax

[form.]Report.ReportSource

For example:

CrystalReport1.ReportSource = 1

«Specifies the report source as the TrueDBGrid control.»

Data Type

Integer

Availability

Design Time and Runtime

Remarks

This property/method is available for subreports.


ReportStartPage

ReportStartPage specifies the first page printed in the specified report.

Syntax

[form.]Report.ReportStartPage

For example:

StartPage% = CrystalReport1.ReportStartPage

«Fetches the number of the first page printed and stores it in the StartPage variable.»

Data Type

Integer

Availability

Runtime

Remarks

This property/method is available for subreports.

Related Report Engine Functions

PEGetJobStatus


ReportTitle

ReportTitle specifies a title for the report.

Syntax

[form.]Report.ReportTitle[= rptTitle$]

For example:

CrystalReport1.ReportTitle = "My Report"

«Applies the title "My Report" to the report.»

Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PESetReportSummaryInfo


SectionFont

SectionFont specifies the font for one or more sections in the specified report.

Syntax
[form.]Report.SectionFont(SequentialIndex%)[= sectionCode; fontName;
size; italic; bold;underline;strikethru$]

For example:

CrystalReport1.SectionFont(0)="Footer;Arial;12;N;N;N;Y"

«Sets the font for the footer section to 12 point, Arial, strikethrough.»

Remarks
  • With SectionFont, you can specify changes to one or more sections at runtime. Those changes then take place sequentially when you make the "Action=1" call.
  • The array index value for SectionFont simply specifies the sequence number for the change. Thus:

    CrystalReport1.SectionFont(0)= "DETAIL;Arial;12;N;N;N;Y"

    when making changes to the DETAIL section only, but

    CrystalReport1.SectionFont(0) = "HEADER;Arial;12;N;N;N;Y"
    CrystalReport1.SectionFont(1) = "DETAIL;Arial;12;N;N;N;Y"

    when making changes to more than one section.

Use the following table as a guide in supplying the required values for this property:

Parameter | Data type | Value expected
sectionCode | string | Please refer to the Overview of Section Codes.
fontName | string | The actual font name (i.e., Arial or Helvetica).
size | number | The size of the font in points (i.e., 12 or 16).
italic | character | T = true, F = False, X = as is*
bold | character | T = true, F = False, X = as is*
underline | character | T = true, F = False, X = as is*
strikethrough | character | T = true, F = False, X = as is*

*X (as is) uses the value saved with the report.

Data Type

Array of strings

Availability

Runtime

Related Report Engine Functions

PESetFont


SectionFormat

SectionFormat specifies the format for one or more sections in the specified report.

Syntax
[form.]Report.SectionFormat(SectionArrayIndex%)[= sectionCode; visible;
newPageBefore; newPageAfter; keepTogether; SuppressBlankSection;
resetPageNAfter; printAtBottomOfPage; underlaySection; backgroundColor]

For example:

CrystalReport1.SectionFormat(0)= "GH2;F;X;X;X;X;X;X;X;255.0.0"

«Hides the Group Header 2 section (visible = F) and changes the background color to red while maintaining default settings for all other switches.»
Remarks

With SectionFormat, you can specify changes to one or more sections at runtime. Those changes then take place sequentially when you make the "Action=1" call. The sequential index value for SectionFormat simply specifies the sequence number for the change. Thus:

CrystalReport1.SectionFormat(0)= "DETAIL;T;F;F;X;X;X;X;X;255.0.0"

when making changes to the DETAIL section only, but

CrystalReport1.SectionFormat(0) = "HEADER;T;F;F;X;X;X;X;X;255.0.0"

CrystalReport1.SectionFormat(1) = "DETAIL;T;F;F;X;X;X;X;X;255.0.0"

when making changes to more than one section.

Use the following table as a reference when entering parameter values for this property:

sectionCode | Please refer to the Overview of Section Codes.
Visible | T = true, F = False, X = as is*
newPageBefore | T = true, F = False, X = as is*
newPageAfter | T = true, F = False, X = as is*
keepTogether | T = true, F = False, X = as is*
suppressBlank | T = true, F = False, X = as is*
resetPageNAfter | T = true, F = False, X = as is*
printAtPageBottom | T = true, F = False, X = as is*
underlaySection | T = true, F = False, X = as is*
backgroundColor | Supply a RGB (Red, Green, Blue) value in the following format: <R>.<G>.<B> where R, G, and B are each integers with a range from 0 to 255. For example: 189.210.100. If you do not want to change the color, do not place anything in this parameter.

* X (as is) uses the settings saved with the report.

Data Type

Arrays of strings

Availability

Runtime

Related Report Engine Functions

PESetSectionFormat


SectionLineHeight

SectionLineHeight specifies the line height in twips.

Syntax
[form.]Report.SectionLineHeight(SequentialIndex%)[=sectionCode; line;
height; ascent$]

For example:

CrystalReport1.SectionLineHeight(0) = "GH0; 1; 500; 300"

«Sets the line height for the second line in the group header zero section to a height of 500 twips with an ascent of 300 twips.»

Remarks

A twip is 1/1440 inch; there are 20 twips in a point.

With SectionLineHeight, you can specify changes to one or more sections at runtime. Those changes then take place sequentially when you make the "Action=1" call. The sequential index value for SectionLineHeight simply specifies the sequence number for the change. Thus:

CrystalReport1.SectionLineHeight(0)= "DETAIL;1;500;300"

when making changes to the DETAIL section only, but

CrystalReport1.SectionLineHeight(0) = "HEADER;1;500;300"

CrystalReport1.SectionLineHeight(1) = "DETAIL;1;500;300"

when making changes to more than one section.

Use the following table as a guide in supplying the required values for this property:

section Code | Specifies the section code for the report section(s) for which you want to set a new line height. See Overview of Section Codes.
lineN | Specifies the line(s) for which you want to set the line height. Line numbers in a section are 0 origin: the first line number is 0, the second is 1, etc.
height | Specifies the line height in twips. A twip is 1/1440 inch; there are 20 twips in a point.
ascent | Specifies the ascent in twips. Ascent is the distance from the top of the allotted line space (line height) to the baseline of the font. The ascent parameter is used to specify the position of the baseline if you specify an oversized or undersized line height. If you set ascent to 0, the program puts the baseline at the top of the space; if you set ascent to the same value as height, the program sets the baseline at the bottom of the space. For any other baseline, specify the ascent in twips.

Data Type

Arrays of strings

Availability

Runtime


SectionMinHeight

SectionMinHeight specifies the minimum section height for the specified report section.

Syntax
[form.]Report.SectionMinHeight
(SequentialIndex%)[=sectionCode;minHeight$]

For example:

CrystalReport1.SectionMinHeight(0) = "DETAIL;500"

«Sets the minimum height for details section to 500 twips.»

Remarks
  • With SectionMinHeight, you can specify changes to one or more sections at runtime. Those changes then take place sequentially when you make the "Action=1" call.
  • The array index value for SectionMinHeight simply specifies the sequence number for the change. Thus:

    CrystalReport1.SectionMinHeight(0)= "DETAIL;500"

    when making changes to the DETAIL section only, but

    CrystalReport1.SectionMinHeight(0) = "HEADER;500"
    CrystalReport1.SectionMinHeight(1) = "DETAIL;500"

    when making changes to more than one section.

Data Type

Array of strings

Availability

Runtime

Related Report Engine Functions

PESetNDetailCopies


SelectionFormula

SelectionFormula specifies the records to be used when printing the report.

Syntax

[form.]Report.SelectionFormula[= SelectionFormula$]

For example:

CrystalReport1.SelectionFormula = "{file.QTY} > 5"

«Include only those records that have a quantity greater than 5 in the {file.Qty} field.»

Remarks
  • Enter the selection formula just as you would enter it in the Formula Editor.
  • Make certain that you enclose your selection formula in double quotes.
  • If your selection formula includes internal quotes, for example:

{file.STATE} = "CA"

change all of the internal double quotes to single quotes and then surround the entire selection formula in double quotes as follows:

"{file.STATE} = 'CA'"

  • If you have created a selection formula in your report at Design Time, any selection formula you enter here will be appended to that selection formula. Thus, your records will be selected based on a combination of the two selection formulas.
Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PESetSelectionFormula


SessionHandle

SessionHandle specifies the session handle for a user once the UserName, and Password, properties have opened an Access.mdb file for use by the report.

Syntax

[form.]Report.SessionHandle[= Handle%]

Remarks

If you have already opened a Jet session in your Visual Basic application, you can set this property to be the current session handle. Otherwise, you will have to use the Password and UserName properties to establish the Jet session.

For example:

CrystalReport1.SessionHandle = CurrentSessionHandle

«Sets the session handle to the session handle returned elsewhere in the application and stored in the variable CurrentSessionHandle.»

Data Type

Integer

Availability

Runtime

Related Report Engine Functions

PESetNthTableSessionInfo


SortFields

SortFields specifies the field(s) that are to be used to sort your data when the report is printed.

Syntax

[form.]Report.SortFields(ArrayIndex)[= "{+|-} SortField"]

Enter the fields on which you want the data in your report to be sorted.

For example, to sort an order database alphabetically by customer, and then by order date, you can enter code similar to the following:

CrystalReport1.SortFields(0) = "+{orders.CUSTOMER}"

CrystalReport1.SortFields(1) = "+{orders.ORDERDATE}"
Remarks
  • SortFields is an array property available only at runtime.
  • Use a separate line of code to specify each sort field.
  • Enter sort fields in the order that you want them to sort your report. For example, if you want your report to be sorted first on field A and then on field B, specify sort field A in your first line of code and sort field B in your second line of code.
  • The sort field you specify must be assigned array index 0, the second sort field must be assigned array index 1, etc.
  • The index values you assign must be continuous; no gaps are allowed (0, 1, 2 = OK, 0, 1, 3 = wrong).
  • Array index values must be subscripted in the code immediately after the property name (i.e., CrystalReport1.SortFields(0) =).
  • If you have specified sort fields for your report at Design Time, any sort fields you enter here will replace the sort fields in your report.
  • If you do not use this property, the program will use the sorting instructions that you specified in the report.
  • If you want to clear the sort fields in your report, use an empty string (i.e., CrystalReport1.SortFields(0) = "").
  • Enclose field names in braces.
  • Sort fields can be database fields or formula fields. If you sort on a formula field, use the @ sign before the formula name (i.e., {@FORMULANAME}).
Data Type

Array of strings

Availability

Runtime

Related Report Engine Functions

PESetNthSortField


SQLQuery

SQLQuery specifies the SQL query string used by the specified report.

Syntax

[form.]Report.SQLQuery[=SQLQuery$]

For example:

CrystalReport1.SQLQuery = "SELECT authors.au_id, authors.au_lname,
authors.au_fname FROM pubs2.dbo.authors authors WHERE authors.au_lname >
'Madison'"

«Queries the SQL database to return only the records where the authors last name falls after Madison alphabetically.»
Remarks
  • You may only change the WHERE, FROM, and ORDER BY sections of an SQL query. Although the property requires that you enter the entire SQL query, the SELECT section must not be different from the original query in the report.
  • To change the ORDER BY clause, you must place a carriage return and linefeed characters after the WHERE clause and before the ORDER BY clause in this way:
CrystalReport1.SQLQuery="SELECT...FROM...

WHERE..." + CHR$(13) + CHR$(10) + "ORDER BY..."
  • This property is active only if you are using an SQL or ODBC data source in your report.
Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PEGetSQLQuery


Status

Status indicates the print status for the specified report.

Syntax

[form.]Report.Status

For example:

Status% = CrystalReport1.Status

«Fetches the print status and saves it to the Status variable.»

Remarks

The Status property will return one of the following values:

  • "0" if PEOpenEngine or PEOpenPrintJob has not been called successfully.
  • "1" if the job has not started yet (PE_JOBNOTSTARTED).
  • "2" if the job is in progress (PE_JOBINPROGRESS).
  • "3" if the job has completed successfully (PE_JOBCOMPLETED).
  • "4" if the job has failed (PE_JOBFAILED).
  • "5" if the job has been canceled by the user (PE_JOBCANCELLED).
  • "6" if the job has been halted (PE_JOBHALETED).

This property/method is available for subreports.

Data Type

Integer

Availability

Runtime

Related Report Engine Functions

PEGetSQLQuery


StoredProcParam

StoredProcParam specifies the stored procedure parameters when using a report based on SQL stored procedures.

Syntax

[form.]Report.StoredProcParam(Parameter Array Index%)[= newParameter$]

For example:

CrystalReport1.StoredProcParam(0)="06/14/1989"

«Sets the first stored procedure parameter to the date June 14, 1989.»

Remarks

StoredProcParam sets the value of the specified parameter in an SQL database table that is based on a stored procedure. Pass the value you wish to set the parameter to as a string. If the parameter expects a different data type, you still must pass the value as a string. For example, to pass the integer value 396, use the string "396". The Crystal Report Engine will handle converting the value into integer format.

Note:

  • Under the native driver for MS SQL Server, stored procedure input parameters are limited to 64 characters rather than 255.
Data Type

Arrays of strings

Availability

Runtime

Related Report Engine Functions

PESetNthParameterDefaultValue


SubreportToChange

SubreportToChange specifies whether changes to any of several properties (see list in Remarks below) affect the main report (if you pass an empty string [""]) or a subreport (if you pass the name of the subreport).

Syntax

[form.]Report.SubreportToChange(= SubreportName$)

For example:

CrystalReport1.SubreportToChange = ""

«Changes to any of the properties apply to the main report.»

CrystalReport1.SubreportToChange = "Subrpt2"

«Changes to any of the properties apply to the Subrpt2 subreport.»

Remarks
  • The following properties are affected by this property:

    Connect

    LogonInfo

    SectionFormat

    DataFiles

    MarginBottom

    SectionLineHeight

    DetailCopies

    MarginLeft

    SectionMinHeight

    Formulas

    MarginRight

    SelectionFormula

    GraphData

    MarginTop

    SessionHandle

    GraphOptions

    Password

    SortFields

    GraphText

    PrintDay

    SQLQuery

    GraphType

    PrintMonth

    StoredProcParam

    GroupCondition

    PrintYear

    UserName

    GroupSelectionFormula

    ReportTitle

    GroupSortFields

    SectionFont

  • If the SubreportToChange property is set to:
      • the empty string, changing any of these properties affects the main report.
      • the name of a subreport, changing any of these properties affects the subreport.
  • When you change the value of the SubreportToChange property, the current value of the properties in the list are updated to be what has been set for the selected subreport.
  • Calling the ReplaceSelectionFormula method will apply the new selection formula to the currently selected subreport.

Note:

  • These properties only reflect values set by the programmer; they do not get values from the report.
Data Type

String

Availability

Runtime


UserName

UserName specifies the name given to a user for logging on to a protected Access.mdb file in order to obtain data files needed by the report.

Syntax

[form.]Report.UserName[= Name$]

For example:

CrystalReport1.UserName = "MIS"

«Enters the user name "MIS".»

Remarks
  • Enter the name you have been assigned.
  • The name must be enclosed in quotes if the variable is being assigned at runtime.
Data Type

String

Availability

Runtime

Related Report Engine Functions

PESetNthTableSessionInfo


WindowAllowDrillDown

WindowAllowDrillDown indicates whether or not drill-down on summary values is allowed in the preview window.

Syntax

[form.]Report.WindowAllowDrillDown[= {True|False}]

For example:

CrystalReport1.WindowAllowDrillDown = FALSE

«Drill-down is not allowed in the preview window.»

Remarks

This property is set to False by default.

Data Type

Boolean

Availability

Design Time; Runtime

Related Report Engine Functions

PESetWindowOptions


WindowBorderStyle

WindowBorderStyle specifies the type of border for the preview window.

Syntax

[form.]Report.WindowBorderStyle[= BorderStyle%]

For example:

CrystalReport1.WindowBorderStyle = 2

«Sets a sizable border style (Style #2) for the preview window.»

Remarks

Select one of the following border styles for the preview window:

  • 0 = None (creates a window with no border).
  • 1 = Fixed Single (creates a window of a fixed size with a single line border).
  • 2 = Sizeable (creates a window that can be resized by the user).
  • 3 = Fixed Double (creates a window of fixed size with a double line border).

Select a value here only if you are printing to a window, if Destination, is set to 0.

Data Type

Integer (Enumerated)

Availability

Design Time; Runtime

Related Report Engine Functions

PEOutputToWindow


WindowControlBox

WindowControlBox to specify whether or not the preview window is to have a control (system menu) box in the upper left hand corner when the report is printed to a window.

Syntax

[form.]Report.WindowControlBox[= {True|False}]

For example:

CrystalReport1.WindowControlBox = True

«Specifies that a control box (system menu) is to appear in the preview window.»

Remarks
  • Select True if you want the window to contain a control box. Select False if you do not.
  • Select a value here only if you are printing to a window, if Destination, is set to 0.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PEOutputToWindow


WindowControls

WindowControls indicates whether or not the print controls are to appear in the preview window when printing a report to a window.

Syntax

[form.]Report.WindowControls[={True|False}]

For example:

CrystalReport1.WindowControls = True

«Specifies that print controls are to appear in the preview window.»

Remarks
  • Select True if you want the print controls to appear in the preview window.
  • Select a value here only if you are printing to a window, if Destination, is set to 0.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PEShowPrintControls


WindowHeight

WindowHeight specifies the height of the preview window when the report is printed to a window.

Syntax

[form.]Report.WindowHeight[= Height%]

For example;

CrystalReport1.WindowHeight = 300

«Sets the height of the preview window to 300 pixels.»

Remarks
  • If you are not satisfied with the default settings, enter the external height you want for your preview window in pixels. (A standard VGA monitor is 640 x 480 pixels.)
  • Select a value here only if you are printing to a window, if Destination, is set to 0.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PEOutputToWindow


WindowLeft

WindowLeft specifies the distance, in pixels, that the preview window is to appear from the left edge of the parent window. If the preview window is a top level window, then the distance is measured from the left edge of the screen. (A standard VGA monitor is 640 x 480 pixels).

Syntax

[form.]Report.WindowLeft[= Distance%]

For example:

CrystalReport1.WindowLeft = 100

«Sets the left edge of the preview window 100 pixels from the left edge of the screen.»

Remarks
  • If you are not satisfied with the default settings, enter the number of pixels you want between the left edge of the screen and the left edge of your window.
  • Select a value here only if you are printing to a window, if Destination, is set to 0.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PEOutputToWindow


WindowMaxButton

WindowMaxButton indicates whether or not the preview window is to have an active, hidden, or grayed-out maximize button when the report is printed to a window.

Syntax

[form.]Report.WindowMaxButton[= {True|False}]

For example:

CrystalReport1.WindowMaxButton = False

«Specifies that no Maximize button is to appear in the preview window (in Windows 95, NT4+). Specifies that the Maximize button will appear grayed out in the preview window (in Windows 3.x)»

Remarks
  • Select True if you want the window to contain a maximize button. Select False if you do not.
  • Select a value here only if you are printing to a window, if Destination, is set to 0.
  • If you set both WindowMaxButton and WindowMinButton, to False, the buttons will not appear at all (be hidden).
  • If you set one of WindowMaxButton or WindowMinButton to True, the other button will appear grayed out.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PEOutputToWindow


WindowMinButton

WindowMinButton indicates whether or not the preview window is to have an active, hidden, or grayed-out minimize button when the report is printed to a window.

Syntax

[form.]Report.WindowMinButton[= {True|False}]

For example:

CrystalReport1.WindowMinButton = True

«Specifies that a Minimize button is to appear in the preview window (in Windows 95, NT4+). Specifies that the Minimize button will be active (no grayed out) in the preview window (in Windows 3.x).»

Remarks
  • Select True if you want the window to contain a minimize button. Select False if you do not.
  • Select a value here only if you are printing to a window, if Destination, is set to 0.
  • If you set both WindowMaxButton, and WindowMinButton to False, the buttons will not appear at all (be hidden).
  • If you set one of WindowMaxButton or WindowMinButton to True, the other button will appear grayed out.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PEOutputToWindow


WindowParentHandle

WindowParentHandle specifies the handle of the parent window if the preview window is to be the child of another window.

Syntax

[form.]Report.WindowParentHandle[= ParentHandle%]

For example:

CrystalReport1.WindowParentHandle = Form1.hWnd

«Sets the WindowParentHandle to the handle of Form1. This specifies that the preview window is to be a child of Form1.»

Remarks

This is a runtime-only property.

Data Type

Integer

Availability

Runtime

Related Report Engine Functions

PEOutputToWindow


WindowShowCancelBtn

WindowShowCancelBtn indicates whether or not a Cancel button is available in the preview window.

Syntax

[form.]Report.WindowShowCancelBtn[= {True|False}]

For example:

CrystalReport1.WindowShowCancelBtn = False

«No Cancel button is displayed in the preview window.»

Remarks

This property is set to False by default.

Data Type

Boolean

Availability

Design Time; Runtime

Related Report Engine Functions

PESetWindowOptions


WindowShowCloseBtn

WindowShowCloseBtn indicates whether or not a Close button is available in the preview window.

Syntax

[form.]Report.WindowShowCloseBtn[= {True|False}]

For example:

CrystalReport1.WindowShowCloseBtn = True

«A Close button will appear in the preview window.»

Remarks

This property is set to False by default.

Data Type

Boolean

Availability

Design Time; Runtime

Related Report Engine Functions

PESetWindowOptions


WindowShowExportBtn

WindowShowExportBtn indicates whether or not an Export button is available in the preview window.

Syntax

[form.]Report.WindowShowExportBtn[= {True|False}]

For example:

CrystalReport1.WindowShowExportBtn = True

«The Export button appear in the preview window.»

Remarks

This property is set to True by default.

Data Type

Boolean

Availability

Design Time; Runtime

Related Report Engine Functions

PESetWindowOptions


WindowShowGroupTree

WindowShowGroupTree indicates whether or not a Group Tree is displayed in the preview window.

Syntax

[form.]Report.WindowShowGroupTree[= {True|False}]

For example:

CrystalReport1.WindowShowGroupTree = False

«No Group Tree is displayed in the preview window.»

Remarks

This property is set to False by default.

Data Type

Boolean

Availability

Design Time; Runtime

Related Report Engine Functions

PESetWindowOptions


WindowShowNavigationCtls

WindowShowNavigationCtls indicates whether or not the Navigation Controls are available in the preview window.

Syntax

[form.]Report.WindowShowNavigationCtls[= {True|False}]

For example:

CrystalReport1.WindowShowNavigationCtls = True

«The preview window contains Navigation Controls.»

Remarks

This property is set to True by default.

Data Type

Boolean

Availability

Design Time; Runtime

Related Report Engine Functions

PESetWindowOptions


WindowShowPrintBtn

WindowShowPrintBtn indicates whether or not a Print button is available in the preview window.

Syntax

[form.]Report.WindowShowPrintBtn[= {True|False}]

For example:

CrystalReport1.WindowShowPrintBtn = False

«No Print button is available in the preview window.»

Remarks

This property is set to True by default.

Data Type

Boolean

Availability

Design Time; Runtime

Related Report Engine Functions

PESetWindowOptions


WindowShowPrintSetupBtn

WindowShowPrintSetupBtn indicates whether or not a Print Setup button is available in the preview window.

Syntax

[form.]Report.WindowShowPrintSetupBtn[= {True|False}]

For example:

CrystalReport1.WindowShowPrintSetupBtn = False

«No Print Setup button is available in the preview window.»

Remarks
  • This property is set to False by default.
  • The Print Setup button displays the Print Setup dialog box, allowing users to make changes to printer settings before printing a report that appears in the preview window.
  • If the Print Setup button is disable, and the Print button is enabled (see WindowShowPrintBtn), when a user clicks the Print button, the report will be sent to the printer selected when the report was created. If no printer was selected, or if the printer is unavailable, the report will be sent to the default printer for the current machine.
Data Type

Boolean

Availability

Design Time; Runtime

Related Report Engine Functions

PESetWindowOptions


WindowShowProgressCtls

WindowShowProgressCtls indicates whether or not controls indicating the progress of a report being generated are displayed in the preview window.

Syntax

[form.]Report.WindowShowProgressCtls[= {True|False}]

For example:

CrystalReport1.WindowShowProgressCtls = False

«No Progress Controls are displayed in the preview window.»

Remarks

This property is set to True by default.

Data Type

Boolean

Availability

Design Time; Runtime

Related Report Engine Functions

PESetWindowOptions


WindowShowRefreshBtn

WindowShowRefreshBtn indicates whether or not a Refresh button is available in the preview window.

Syntax

[form.]Report.WindowShowRefreshBtn[= {True|False}]

For example:

CrystalReport1.WindowShowRefreshBtn = False

«No Refresh button is displayed in the preview window.»

Remarks
  • This property is set to False by default.
  • The Refresh button allows a user to refresh the data displayed in a report. The most current data can be obtained by refreshing report data, but the process of accessing the database containing the data can be time consuming and may burden system and network resources.
Data Type

Boolean

Availability

Design Time; Runtime

Related Report Engine Functions

PESetWindowOptions


WindowShowSearchBtn

WindowShowSearchBtn indicates whether or not a Search button is available in the preview window.

Syntax

[form.]Report.WindowShowSearchBtn[= {True|False}]

For example:

CrystalReport1.WindowShowSearchBtn = True

«The Search button is displayed in the preview window.»

Remarks
  • This property is set to False by default.
  • The Search button allows a user to search for a specific field value in the report.
Data Type

Boolean

Availability

Design Time; Runtime

Related Report Engine Functions

PESetWindowOptions


WindowShowZoomCtl

WindowShowZoomCtl indicates whether or not Zoom Controls are available in the preview window.

Syntax

[form.]Report.WindowShowZoomCtl[= {True|False}]

For example:

CrystalReport1.WindowShowZoomCtl = True

«Zoom Controls are displayed in the preview window.»

Remarks
  • This property is set to True by default.
  • Zoom controls allow a user to zoom in or out on report data, enlarging or reducing the report on screen.
Data Type

Boolean

Availability

Design Time; Runtime

Related Report Engine Functions

PESetWindowOptions

WindowState

WindowState specifies the state of the preview window (normal, minimized, or maximized) when the report is printed.

Syntax

[form.]Report.WindowState[= State%]

For example:

CrystalReport1.WindowState= 2

«When the report is printed to a preview window, the preview window appears maximized when opened.»

Remarks

Use the following values to set the WindowState property:

  • 0 = Normal
    The preview window appears neither minimized nor maximized. It appears in a default size and position previously defined by your application or by Windows.
  • 1 = Minimized
    The preview window appears minimized as an icon close to the lower left hand corner of the screen. The icon can be restored to display the window in a normal state.
  • 2 = Maximized
    The preview window is maximized when opened to fill the entire screen.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PEOutputToWindow


WindowTitle

WindowTitle specifies the title that you want to appear in the preview window title bar when the report is printed to a window.

Syntax

[form.]Report.WindowTitle[= Title$]

For example:

CrystalReport1.WindowTitle = "Quarterly Earnings"

«Sets the title of the preview window (the string that appears on the title bar) to "Quarterly Earnings".»

Remarks
  • Make sure that the title is enclosed in quotes.
  • Select a value here only if you are printing to a window, if Destination, = 0.
Data Type

String

Availability

Design Time; Runtime

Related Report Engine Functions

PEOutputToWindow


WindowTop

WindowTop specifies the distance, in pixels, that the preview window is to appear from the top edge of the parent window. If the preview window is a top level window, then the distance is measured from the top edge of the screen.

Syntax

[form.]Report.WindowTop[= Distance%]

For example:

CrystalReport1.WindowTop = 100

«Sets the top edge of the preview window 100 pixels from the top of the screen.»

Remarks
  • If you are not satisfied with the default setting, enter the number of pixels you want between the top of the screen and the top of your window.
  • Select a value here only if you are printing to a window, if Destination, is set to 0.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PEOutputToWindow


WindowWidth

WindowWidth specifies the width of the preview window in pixels.

Syntax

[form.]Report.WindowWidth[= Width%]

For example:

CrystalReport1.WindowWidth = 480

«Specifies a preview window 480 pixels wide.»

Remarks
  • If you are not satisfied with the default setting, enter the external width of your window, in pixels.
  • Select a value here only if you are printing to a window, if Destination, is set to 0.
Data Type

Integer

Availability

Design Time; Runtime

Related Report Engine Functions

PEOutputToWindow


ActiveX Controls Methods

The following Methods are discussed in this section:

  • FetchSelectionFormula.
  • GetNSubreports.
  • GetNthSubreportName.
  • LogoffServer.
  • LogonServer.
  • PageCount.
  • PageFirst.
  • PageLast.
  • PageNext.
  • PagePrevious.
  • PageShow.
  • PageZoom.
  • PageZoomNext.
  • PrinterSelect.
  • PrintReport.
  • ReplaceSelectionFormula.
  • Reset.
  • RetrieveDataFiles.
  • RetrieveLogonInfo.
  • RetrieveSQLQuery.
  • RetrieveStoredProcParams.
  • SpecifyDataSourceField.


FetchSelectionFormula

FetchSelectionFormula returns the selection formula from the current report.

Syntax

[form.]Report.FetchSelectionFormula

For example:

SelectionFormula$= CrystalReport1.FetchSelectionFormula

«Retrieves the selection formula from CrystalReport1.»

Remarks

This method does not populate SelectionFormula, and it does not conflict with setting the property. Both the method and the property can be used in the same code.

Availability

Runtime only


GetNSubreports

GetNSubreports looks at the report specified in ReportFileName, and returns the number of subreports in that report.

Syntax

[form.]Report.GetNSubreports

For example:

Number=CrystalReport1.GetNSubreports

«Returns the number of subreports in CrystalReport1.»

Remarks

Seagate Software IMG Holdings, Inc.
http://www.seagatesoftware.com
Support services:
http://support.seagatesoftware.com


GetNthSubreportName

GetNthSubreportName looks at the report specified in the ReportFileName property and returns a string which is the name of the nth subreport in that report.

Syntax

[form.]Report.GetNthSubreportName (SubreportNum%)

For example:

SubreportName=CrystalReport1.GetNthSubreportName (2)

«Returns the name of the third subreport in CrystalReport1.»

Remarks

The valid range for the parameter is 0 to n-1, where n is the number you get back from GetNSubreports.


LogoffServer

LogoffServer terminates the specified database connection established earlier with the LogonServer.

Syntax

[form.]Report.LogoffServer (connectionId%, boolean allConnections)

For example:

CrystalReport1.LogoffServer (1, False)

«Terminates database connection 1 and only that connection.»

Parameters

connectionId

Integer value that specifies a specific database connection established earlier with LogonServer. If you have set allConnections to True, connectionId should be set to 0.

allConnections

Boolean value that specifies whether or not to terminate ALL database connections that have been established with the LogonServer method.

  • True = Terminate all connections.
  • False = Terminate only the specified connection.


LogonServer

LogonServer logs on to the specified server and returns a unique connection id which can be used to log off of this server using the LogoffServer.

Syntax

[form.]Report.LogonServer (dllName$, ServerName$, DatabaseName$, UserID$, Password$)

For example:

connectionId% = CrystalReport1.LogonServer ("pdsodbc.dll", "Accounting", "Administration", "bobg", "bigboard")

«Connects to the "Administration" database via the "Accounting" data source using the user ID "bobg" and the password "bigboard".»

Parameters

dllName

Specifies the name of the Crystal Reports DLL for the server or password protected non-SQL table you want to log onto, for example, "PDSODBC.DLL". Note that the dllName must be enclosed in quotes. DLL names have the following naming convention:

  • PDB*.DLL for standard (non-SQL) databases.
  • PDS*.DLL for SQL/ODBC databases.

ServerName

Specifies the logon name for the server used to create the report. *For ODBC, use the data source name.

DatabaseName

Specifies the logon name for the database used to create the report.

UserID

Specifies the user ID necessary to log on to the server.

Password

Specifies the password necessary to log on to the server. When you are using this structure to retrieve information using PEGetNthTableLogOnInfo, the password parameter is undefined.


PageCount

PageCount returns the number of pages in the report.

Syntax

[form.]Report.PageCount

For example:

NumberofPages = CrystalReport1.PageCount

«Returns 100 if the number of pages in the specified report is 100.»

Remarks

PageCount must be called after the Action, to get a valid page count.


PageFirst

PageFirst displays the first page of the report in the preview window.

Syntax

[form.]Report.PageFirst

For example:

CrystalReport1.PageFirst

«Displays the first page of the report to the preview window.»

Remarks
  • This method is only valid when the report is printed to a preview window.
  • This method must be called after the Action.


PageLast

PageLast displays the last page of the report in the preview window.

Syntax

[form.]Report.PageLast

For example:

CrystalReport1.PageLast

«Displays the last page of the report in the preview window.»

Remarks
  • This method is only valid when the report is printed to a preview window.
  • This method must be called after the Action.


PageNext

PageNext displays the next page of the report in the preview window.

Syntax

[form.]Report.PageNext

For example:

CrystalReport1.PageNext

«Displays the next page of the report in the preview window.»

Remarks
  • This method is only valid when the report is printed to a preview window.
  • This method must be called after the Action.


PagePrevious

PagePrevious displays the previous page of the report in the preview window.

Syntax

[form.]Report.PagePrevious

For example:

CrystalReport1.PagePrevious

«Displays the previous page of your report in the preview window.»

Remarks
  • This method is only valid when the report is printed to a preview window.
  • This method must be called after the Action.


PageShow

PageShow displays a specific page of the report in the preview window.

Syntax

[form.]Report.PageShow [(PageToShow%)]

For example:

CrystalReport1.PageShow (3)

«Shows the third page of the report.»

Remarks
  • This method is only valid when the report is printed to a preview window.
  • This method must be called after the Action.


PageZoom

PageZoom sets the magnification factor for the report in the preview window to a value from 25% to 400% of the actual size.

Syntax

[form.]Report.PageZoom [(PercentZoomLevel%)]

For example:

CrystalReport1.PageZoom (150)

«Sets the magnification/zoom level to 150% for the current.»

Remarks
  • This method is only valid when the report is printed to a preview window.
  • This method must be called after the Action.


PageZoomNext

PageZoomNext zooms the magnification level of the report in a preview window to the next default zoom level.

Syntax

[form.]Report.PageZoomNext

For example:

CrystalReport1.PageZoomNext

«Sets the magnification/zoom level to the next default level.»

Remarks
  • This method is only valid when the report is printed to a preview window.
  • This method must be called after the Action.
  • Default zoom levels are Full Page, Fit One Side, and Fit Both Sides. These levels correspond to the levels available by clicking the Zoom button on the Crystal Reports toolbar.


PrinterSelect

PrinterSelect displays the Printer Selection common dialog box which enables the user to specify a different printer.

Syntax

[form.]Report.PrinterSelect

For example:

CrystalReport1.PrinterSelect

«When the user prints, a dialog box appears for selecting the desired printed for printing the report.»

Remarks
  • This method allows you to pick the printer used for printing the report.
  • This method is intended primarily for printing reports to a printer. However, changes made to the Print Setup dialog box may also affect how reports appear in preview windows and when exported.


PrintReport

PrintReport triggers the printing of the report.

Syntax

[form.]Report.PrintReport

For example:

Result% = CrystalReport1.PrintReport

«Prints the specified report.»

Remarks
  • PrintReport returns a result code, 0 if the call is successful, an error code in the 20XXX range if it fails.
  • You can also print a report using the Action. If something goes wrong, however, you get a runtime error that will terminate your application. For this reason, you will need to set up an error handler.
Availability

Runtime

Related Report Engine Functions

PEStartPrintJob


ReplaceSelectionFormula

ReplaceSelectionFormula overrides the selection formula from the current report with the string that is passed.

Syntax

[form.]Report.ReplaceSelectionFormula [(SelectionFormulaString$)]

For example:

CrystalReport1.ReplaceSelectionFormula ("{Company.State}='CA'")

«Uses "{Company.State}='CA'" as the selection formula for the report.»

Remarks

This method DOES NOT use the string in SelectionFormula, and DOES conflict with setting the property. You cannot set the SelectionFormula, property and call ReplaceSelectionFormula in the same code sequence. A Visual Basic error condition will be raised in such a case.

Availability

Runtime only


Reset

Reset resets the value of all properties (except DataSource) to their default values.

Syntax

[form.]Report.Reset

For example:

CrystalReport1.Reset

«Returns all properties (except DataSource) for CrystalReport1 to their default values.»


RetrieveDataFiles

RetrieveDatafiles retrieves all "table" locations from the current report, populates DataFiles, and returns the number of "tables" in the report.

Syntax

[form.]Report.RetrieveDatafiles

For example:

NumberofDatafiles% = CrystalReport1.RetrieveDatafiles

«Populates the DataFiles property with the table locations from CrystalReport1.»

Remarks

This method can only be called AFTER ReportFileName, has been set.

Availability

Runtime only


RetrieveLogonInfo

RetrieveLogonInfo retrieves logon information (except for the password) for all "tables" in the current report, populates LogOnInfo, and returns the number of "tables" in the report.

Syntax

[form.]Report.RetrieveLogonInfo

For example:

NumberofTables% = CrystalReport1.RetrieveLogonInfo

«Retrieves the logon information for all the tables in CrystalReport1.»

Remarks

This method can only be called AFTER the ReportFileName, has been set. This method DOES NOT use the string in the Connect property and DOES conflict with setting the property. You cannot set the Connect property and call RetrieveLogonInfo in the same code sequence. A Visual Basic error condition will be raised in this case.

Availability

Runtime only


RetrieveSQLQuery

RetrieveSQLQuery retrieves the SQL Query from the current report and populates SQLQuery.

Syntax

[form.]Report.RetrieveSQLQuery

For example:

CrystalReport1.RetrieveSQLQuery

«Retrieves the SQL query from CrystalReport1.»

Remarks

This method can only be called AFTER ReportFileName, has been set.

Availability

Runtime only


RetrieveStoredProcParams

RetreveStoredProcParams retrieves all stored procedure parameters from the current report, populates StoredProcParam, and returns the number of parameters.

Syntax

[form.]Report.RetrieveStoredProcParams

For example:

NumberofParams% = CrystalReport1.RetrieveStoredProcParams

«Retrieves the stored procedure parameters from CrystalReport1.»

Remarks

This method can only be called AFTER ReportFileName, has been set.

Availability

Runtime only


SetTablePrivateData

The SetTablePrivateData method is used to provide information about a data source to the database driver associated with the reports database at runtime. For instance, if a report has been designed using the Crystal Active Data Driver this method can be used to provide an active data source for the report, such as a DAO, ADO, or RDO Recordset or a CDO Rowset. In this case, the object passed to the third parameter of this method replaces, at runtime, the field definition file used to create the report.

Syntax

[form.]Report.SetTablePrivateData TableIndex% , DataTag&, Data

For Example:

CrystalReport1.SetTablePrivateData 0, 3, rs

Passes a recordset to the first table in the report.

Remarks
  • This method can only be called AFTER ReportFileName, has been set.
  • The first parameter, TableIndex, specifies the index number of the table to be set. Default value = 1.
  • The second parameter, DataTag, is value indicating the type of data being passed to the report in the Data parameter. Currently, the only possible value is 3. This value must be used for all Active data sources including DAO, ADO, RDO, CDO, and the Visual Basic data control.
  • The third parameter, Data, is the variant data passed to the database driver. For example, with Active data, this must be a Recordset object if you are using DAO, ADO, or the Visual Basic data control. This must be a Rowset object if you are using CDO.
Availability

Runtime only.


SpecifyDataSourceField

SpecifyDataSourceField enables you to specify the columns that appear, their order, and their width for reports that are automatically generated from a Data control. If you call this function one or more times, only the columns indicated by the calls will appear in the report. You must call this function one time for each column you are setting.

Syntax

[form.]Report.SpecifyDataSourceField ColumnNum%, ColumnName$, ColumnWidth%

For example:

CrystalReport1.SpecifyDataSourceField (0, "Year Born", 10)
CrystalReport1.SpecifyDataSourceField (1, "Au_ID", 20)

«If the data control was pointing to the Authors table in the Biblio sample, the code results in a report where the first column is year born and the second column is author_id.»
Remarks
  • This method only works when ReportSource = 3, Data Control Fields. It does not work when ReportSource = 1, Bound TrueDBGrid Control.
  • The first parameter, ColumnNum, specifies the column number (zero indexed).
  • The second parameter, ColumnName, is the name of the column as it appears in the data control.
  • The third parameter is the column width, in characters.
  • To use the default width for the type of column, pass -1 as the third parameter.


ActiveX Controls Error Messages

Error # Error Message/Explanation

400

PE_ERR_CONFLICT
LOGON
INFOCONNECT

"Do not use both Connect property and LogonInfo property."
This message appears if you try to set both of these properties at the same time.

401

PE_ERR_REPORTFILENAMENOTSET

"ReportFileName property must be set before calling method."
Some methods retrieve information from a report. This message appears if you try to call these methods before setting the ReportFileName property. The methods are:

  • FetchSelectionFormula
  • ReplaceSelectionFormula
  • RetrieveDataFiles
  • RetrieveSQLQuery
  • RetrieveStoredProcParams
  • GetNSubreports

402

PE_ERR_SELECTION
FORMULACONFLICT

"Do not use both SelectionFormula and ReplaceSelectionFormula."
ReplaceSelectionFormula is a method. This message appears if you attempt to use it after SelectionFormula.

403

PE_ERR_BADDLL

"DLL name must be specified."
This message appears if you call the LogOnServer method and don't specify the DLLname parameter.

404

PE_ERR_STRING
TOOLONG

"A string is too long."
This message appears:

  • if you set an element of the ParameterFields property to a string whose value part is greater than 256 characters, or
  • if you call the LogOnServer method, and the server, database, userid, or password parameters are greater than 128 characters.

405

PE_ERR_BAD
SUBREPORTINDEX

"Invalid Subreport index."
This message appears if you call the method GetNthSubreportName and the first parameter does not correspond to a subreport.

406

PE_ERR_BAD
SUBREPORTNAME

"Unknown Subreport name."
This message appears if you set the SubreportToChange property to the name of a subreport that does not exist in the current report.

407

PE_ERR_ODBCTABLE
NOTSET

"Need ODBC table name for export."
This message appears when you attempt to export to ODBC without setting the PrintFileODBCTable property.


Creating User-Defined Functions in C

Crystal Reports allows you to create User Defined Functions that are recognized by the Crystal Reports Formula Editor. In this section you will find detailed information on programming User Defined Functions in C.

Click the appropriate link to jump to that section:

  • Overview of User-Defined Functions in C
  • Programming User-Defined Functions in C
  • Name of the function
  • Purpose of the function
  • Function data
  • Return types
  • Programming the UFL
  • Setting Up a UFL Project
  • Function Definition
  • Returning User-Defined Errors
  • Obtaining parameter values from the parameter block
  • Picture Function - a sample UFL function
  • Module Definition (.def) File
  • UFJOB Modules
  • Implement InitJob and TermJob


Overview of User-Defined Functions in C

The Crystal Reports Formula Editor and formula language are powerful tools, enabling you to perform a wide variety of report-related tasks easily and efficiently. The formula language is expandable as well. That is, while it already includes a large selection of useful functions, it also comes with the ability to accept new functions that you define to meet your needs.

User-Defined Functions that are recognized by the Crystal Reports Formula Editor can be created in a Dynamic Link Library or, for 32-bit environments, in an Automation Server. This section demonstrates how to create User-Defined Functions in a Dynamic Link Library using the C programming language. For information on how to create User-Defined Functions in an Automation Server using Visual Basic or Delphi, see Creating User-Defined Functions in Visual Basic or Creating User-Defined Functions in Delphi 3.0.


Programming User-Defined Functions in C

You can add new functions to the Crystal Reports Formula Editor by:

  • writing the functions using the C programming language, and
  • compiling and linking the functions into a User-Defined Function DLL called a UFL (User Function Library).

Note: If you are not familiar with programming Windows DLLs, refer to the Microsoft Windows Software Development Kit. Do not attempt to create a UFL if you do not understand Windows DLL programming.

When designing a new function for the Crystal Reports Formula Editor, you need to determine the following:

  • Name of the function
  • Purpose of the function
  • Function data
    the report data or user supplied data that the function will require.
  • Return types
    the type of data that the function will return to the report.


Name of the function

The name of the new function should reflect the function's purpose, making it easier to recognize when it appears in the Formula Editor's Functions list. For example, a function named "Picture" could let you specify a template picture of how data should appear in the report. If a field contains phone numbers, you can use the Picture function to specify that the data appear like this:

(xxx) xxx-xxxx

A resulting value from the phone number field would appear as follows:

(415) 555-1234

Function names must start with a letter, while all remaining characters in the name can be letters or numbers. The name can be up to 254 characters long, and it must be unique. That is, you cannot give a function a name that has been used for another Formula Editor function or UFL function, nor can it have a name that matches a standard C keyword (such as if, return, switch, or while).


Purpose of the function

You may find it helpful to start simply by "fleshing out" your function. Determine the purpose of the function and outline it on paper. Use C code or even pseudocode to determine how the function will perform the required operation. This step is important, as it will form the base information for every other step in the designing and programming of your UFL.


Function data

UFL functions are much like any other function you might create in C. They can accept values that are passed as parameters, and they return a value that is printed on the report. Once you have determined how a UFL function will perform a task, you will know exactly what kind of data it will require to complete that operation. The following table shows the data types that a UFL function can accept as a parameter, along with a description of what the parameter will look like in C:

Parameter Type | C Data Type
number | Double.
currency | Double.
Boolean | Short integer.
string | Pointer to an array of characters.
range (number) | Structure containing two doubles.
range (currency) | Structure containing two doubles.
range (Boolean) | Structure containing two short integers.
range (date) | Structure containing two long integers.
range (string) | Structure containing pointers to two elements in a character array.
array (number) | Pointer to a number array.
array (currency) | Pointer to a number array.
array (integer) | Pointer to an integer array.
array (Boolean) | Pointer to a Boolean array.
array (date) | Pointer to a date array.
array (string) | Pointer to a string array.


Return types

Finally, you must determine what kind of data your function returns to the current report in Crystal Reports. The following table lists the possible UFL return types along with a description of the C data type used when programming the function:

Return Type | C Data Type
string | Pointer to a character array.
number | Double.
date | Long integer.
Boolean | Short integer.
currency | Double.
range (date) | Structure containing two long integers.
range (number) | Structure containing two doubles.
range (currency) | Structure containing two doubles.
range (string) | Structure containing pointers to two elements in a character array.
array (date) | Pointer to a date array.
array (number) | Pointer to a number array.
array (currency) | Pointer to a number array.
array (string) | Pointer to a string array.
array (Boolean) | Pointer to a Boolean array.


Programming the UFL

After sketching out a new function, deciding on its parameters and data types, and determining the type of data the function will return to a report, you can begin programming the UFL.

A UFL is like any other DLL with a few simple differences:

  • Although the file is referred to as a "UFL" it must have a U2L prefix for 32-bit Crystal Reports. For example, U2LSAMP.DLL.
  • it must export your User-Defined Function (UDF) as a DLL function, and
  • it must export a collection of other functions required by Crystal Reports.

You can design your UFL from scratch, but you may find the Helper Modules, provided with Crystal Reports useful. If you use the helper modules provided, you will only need to create a single C code module, a Module Definition (.def) File, and an application project file. More experienced programmers may want to use these modules simply as a starting point to design more complex UFL features.

The "Picture" example

Code for the Picture function is provided as an example of a UFL. The purpose of this function is to display string type field data using a format specified by the user. For example, if the phone number is entered in the database table as "4155551234", the user can create the following formula:

Picture({table.PHONENUM}, "(xxx) xxx-xxxx")

The phone number will appear in the report as: (415) 555-1234

The code segments that appear in this section as examples use this Picture function. In addition, the complete code is listed in Picture Function - a sample UFL function, later in the chapter.


Helper Modules

The files listed below have been installed on your system in the same directory as CRW.EXE (C:\CRW by default).

You do not need to work with the actual code in any of these files, but they will have to be added to your UFL project. UFJOB.H and UFJOB.C are optional files providing job information for the current print job accessing the Formula Editor. For more information, see UFJOB Modules:

File Name | Purpose
ufdll.h | Defines UFL enumerated, union, structure, and other data types.
ufuser.h | Prototypes of tables and functions user must implement.
ufmain.h | Prototypes of internal UFL functions implemented in UFMAIN.C.
uffuncs.h | Prototypes of functions that must be exported by the UFL to be used by Crystal Reports. These functions are implemented in UFMAIN.C.
ufmain.c | Implementation of UFL functions used internally and used by Crystal Reports when connecting to the UFL. This file also contains generic LibMain and WEP functions for Windows 3.x DLLs and a generic DllEntryPoint function for Win32 DLLs. (The LibMain, WEP, and DllEntryPoint functions are defined conditionally according to whether or not you are building a Win32 DLL. You do not need to make any changes to the code here).
ufjob.h | Optional file. Contains a definition of the JobInfo structure see UFJOB Modules, and prototypes of theInitForJob Function, TermForJob Function, and FindJobInfo (see Implement InitJob and TermJob, implemented in UFJOB.C. structure and PROTOTYPES.C.
ufjob.c | Optional file. Contains implementations of the required InitForJob Function and TermForJob Function. Also implements theFindJobInfo helper function.


Setting Up a UFL Project

Begin creating your UFL by setting up a new directory on your system to work in. Use File Manager or Windows Explorer to copy all of the files listed in the chart under Helper Modules, into your new directory. This assures that you do not inadvertently edit or change the original files in your CRW directory.

Note: If you will not be using the functionality provided by UFJOB.H and UFJOB.C, you do not need to copy these files into your working directory.

Now, open your Integrated Development Environment (IDE) application, and use the tools there to create a new project file. Name the new project file with a UFL prefix if your function library will be used with Crystal Reports for Windows 3.x, or with a U2L prefix if it will be used with Crystal Reports for Win32. For example, UFLSAMP.MAK or U2LFUNCS.PRJ. Make sure the project is set to build a DLL (not a Windows EXE) file.

Note: If you are building a 32-bit version of a User Function Library, make sure you set Struct Member Alignment for the project to 1 byte. Crystal Reports for Win32 will not be able to use your UFL otherwise. To find out how to change the Struct Member Alignment setting for your project, refer to the documentation for your development environment.

Finally, add the UFMAIN.C file to your project, and save the project in your new working directory. Add the UFJOB.C file as well if you are using this file. You are now ready to begin creating a new UFL for the Crystal Reports Formula Editor.


Function Definition

Creating a UFL function requires that you create only one more C code module and a module definition (.def) file in addition to the Helper modules. (Your particular UFL Function needs may require more modules, but the simplest method for creating a UFL requires creating only these two.) For information on creating the module definition file, seeModule Definition (.def) File. To begin building your UFL, create a new C module in your IDE, and save it to your working directory with the same name as your project file. For example, if your project file is named UFLSAMP.MAK or UFLFUNCS.PRJ, you would name your C module UFLSAMP.C or UFLFUNCS.C respectively. This demonstration will refer to UFLSAMP.C. This is the "private" C module for your UFL because it is the one section of code that must be unique to your UFL.

The first step to programming your UFL's private C code module is to #include the appropriate header files:

  • #include <windows.h>
  • #include "ufdll.h"
  • #include "ufmain.h"
  • #include "ufuser.h"

You do not need to #include the UFFUNCS.H header file that you also copied into your working directory. This file is already #included by UFMAIN.C, and you will not be directly calling any of the functions defined in these files (though they are necessary for Crystal Reports when the Formula Editor accesses your UFL).

The private C code module of your UFL requires several parts:

  • Function Definition Table,
      • Function definition table example
  • Function Templates Table,
  • Function Examples Table,
  • Error Table,
  • InitForJob Function,
  • TermForJob Function, and
  • UFL Function Implementation.

Most of these sections have specific guidelines that must be used and that are the same for every function you add to your UFL. Your UFL function implementation is completely designed and programmed by you. It is the functionality that you are adding to the Crystal Reports Formula Editor.


Function Definition Table

You must supply a definition for each function that you want to add to Crystal Reports. Each entry in the function definition table consists of a definition string that specifies: the return type,

  • the function name,
  • an argument list (showing the required order in which arguments are to be entered and the data type of each argument), and
  • the name of the C/C++ function that implements the call. The definition must appear with the following format:

    "returnType UDFName (arg1, arg2,...)", CFunctionName

Here is an example:

"String Picture (String, String)", Picture

In this example:

  • "String" specifies that the function is to return a string.
  • "Picture" is the name that will identify the function on the Function list in the Formula Editor.
  • "(String, String)" specifies that the function is to require two arguments, both are strings.
  • "Picture" (appearing after the comma), is the actual function name, the name you give the function when you code it.

Note: The UDFName and the CFunctionName do not have to be the same. You can use something other than the function name to identify a function on the Function list of the Formula Editor if you wish.

All function definitions must be set up in a table with the following heading:

UFFunctionDefStrings FunctionDefStrings [] =

Note: The table must be terminated with three nulls.

Crystal Reports uses the information you supply in this table to create parameter blocks when you call the functions.

Function definition table example

Here is a sample function definition table for the Picture function:

UFFunctionDefStrings FunctionDefStrings [] =

{

    {"String Picture(String,String)",Picture},

    {NULL,NULL,NULL}

};

An optional third parameter can be used when you know the maximum length of the return value (or your code can obtain it).

For example, the definition for the Picture function might be:

{"String Picture (String, String)", Picture, PictureRetSize},

Here, PictureRetSize specifies the maximum acceptable length of the string returned by the Picture function.


Function Templates Table

You must supply a function template for each function that you define. A function template specifies the string that Crystal Reports is to enter in the Formula Editor's Formula text box when you select the function from the Functions list in the Formula Editor. Each template must contain:

  • the function call,
  • any syntax guides (parentheses, commas, etc.) you want to include, and
  • an exclamation point (!) character to specify where the insertion point is to appear when the function is entered into the formula. Here is an example:

"Picture (!, )"

In this example, the string "Picture ( , )" is to be entered into the formula whenever you select the Picture function from the Functions list in the Formula Editor.

  • The string includes the function call "Picture" and the syntax guides "( , )" to guide the user when entering arguments.
  • The exclamation point specifies that the insertion point is to be placed inside the parentheses, before the comma.

All function templates must be set up in a table with the following heading:

UFFunctionTemplates FunctionTemplates [] =

Note: The table must be terminated with a null.

Continuing with the example, the function templates table for the Picture function should look like this:

UFFunctionTemplates FunctionTemplates [] =

{

    {"Picture (!, )"},

    {NULL}

};


Function Examples Table

You must also supply a function example for each function. A function example specifies the string you want to use to identify and select the function in the Functions list in the Formula Editor. Here is a function example for the Picture function:

"\tPicture (string, picture)"

This example specifies that the string "Picture (string, picture)" is the listing that you want to appear in the Functions list. The characters "\t" specify that the string is to be set in from the left one tab stop, thus aligning it with other functions in the list.

All function examples must be set up in a table with the following heading:

UFFunctionExamples FunctionExamples [] =

Note: The table must be terminated with a null.

The complete function examples table for the Picture function should look like this:

UFFunctionExamples FunctionExamples [] =

{

    {"\tPicture (string,picture)"},

    {NULL}

};


Error Table

You must also supply an error string for each error message that you want to make available to your functions. Each error string contains only the text you want to display when an error is detected, and it must be in the format:

"ErrorString"

Note: C compilers view the first string in the table as Error 0, the second as Error 1, etc. Each string in the error table corresponds to an error code that you define. For each user error code, there must be a message string in the error table at the corresponding index, where the first string is at index 0.

Each UFL C function must return a value of the enumerated type UFError, defined in ufdll.h. Return UFNoError if no error occurred. Return one of the other UFError values if there is an error. Try to choose one of the predefined values if it fits your situation. If the error is specific to your UFL, set the ReturnValue.UFReturnUserError member of the parameter block to an error code value you have defined and return UFUserError from your function code. The Formula Editor will then call back to return the error string that you have defined in the error table.

The Formula Editor passes a parameter block to a UFL function rather than individual parameters. Obtaining parameter values from the parameter block, will examine how to handle parameter blocks.

All error strings must be set up in a table with the following heading:

char *ErrorTable [] =

An error table for the Picture function should, at a minimum, look like this:

char *ErrorTable[] =

{

    "no error"

};


InitForJob Function

The InitForJob function initializes all user function UFL's with the job ID whenever a job starts. You can handle any job initialization for your functions here, but all that is absolutely necessary is an empty function implementation:

void InitForJob(UFTInt32u jobID)

{

}

Note: See the note following TermForJob Function.


TermForJob Function

The TermForJob function terminates the job ID for all user function UFL's whenever a job finishes. You can add any job termination code here that you like, but all that is absolutely necessary is an empty function implementation:

void TermForJob(UFTInt32u jobID)

{

}

Note: Every UFL must have an implementation of InitForJob Function, and TermForJob. These functions are called when a job starts and ends printing, respectively. You can choose to implement these yourself. At a minimum, you must provide empty functions.

Crystal Reports provides helper modules (UFJOB.C and UFJOB.H) which implement these functions and maintain a doubly linked list of JobInfo structures, one for each active job. The JobInfo structure (declared in UFJOB.H) holds the ID# of the job and contains a void pointer where you can store any data that you allocate. The files also implement a FindJobInfo function (see Implement InitJob and TermJob, which you can use to retrieve the job information for any open job. UFJOB Modules, will examine these files and their implementation of InitForJob and TermForJob.


UFL Function Implementation

As the final step to creating a UFL function (see Function Definition), you must add code for the operation of the function you have designed. Your function must be programmed for the specific needs of your UFL. This section will examine the basics of how to obtain the parameters from the parameter block and use the values of those parameters in the implementation of the UFL function.

You begin by coding your function as follows:

ExternC UFError FAR _export PASCAL FunctionName

    (UFParamBlock *ParamBlock)

{

    // Your function's code

}

First, notice that the function is exported because a UFL is simply a DLL being accessed by Crystal Reports. Second, the function returns an error code of the enumerated type UFError. In the error trapping sections of your function, you can return a UFError value, such as UFNotEnoughParameters, or you can return UFUserError and define your own errors in the error table. Finally, the function accepts a parameter block of type UFParamBlock from Crystal Reports rather than individual parameters. You will need to retrieve the individual parameters from that parameter block to work with the data values passed by the Formula Editor.

Note: ExternC is defined in UFDLL.H and is equivalent to: extern "C".


Returning User-Defined Errors

The UFError enumerated type provides several errors that are common to many types of functions. If appropriate, have your UFL function return one of these predefined types. If no error occurs, you can return UFNoError.

If your function can cause an error that is not predefined, however, you can establish a user-defined error. You do this by:

  • adding an error string to the error table,
  • passing the appropriate error index to the ReturnValue.UFReturnUserError member of the parameter block, and
  • returning UFUserError from your UFL function implementation.

A user-defined error string in the error table might look like this:

char *ErrorTable[] =

{

    "My User-defined Error"

};

This error string is assigned an error index by Crystal Reports. The first error is 0, the second is 1, etc. If an error occurs in your function, you assign the appropriate index value to the ReturnValue.UFReturnUserError member of the parameter block. For example:

ParamBlock->ReturnValue.UFReturnUserError = 0;

Once you specify a user-defined error, you can return the UFError value UFUserError from your function. When the Formula Editor finds the error in a formula entered in the Formula text box (when the Check or Accept button is clicked), it will use the error index specified to report the appropriate string listed in the error table.


Obtaining parameter values from the parameter block

Since Crystal Reports passes the values for a Formula Editor function's parameters in a parameter block rather than individually, you must separate the values from the parameter block before they can be evaluated. For the Picture function (see Picture Function - a sample UFL function), expect the parameter block to contain two parameters, both of type String, as defined in the function definition table.

To obtain the values of the individual parameters, begin by defining pointers to two structures of type UFParamListElement (defined in UFDLL.H):

UFParamListElement    *FirstParam,

    *SecondParam;

Next, call the GetParam function (defined in UFMAIN.C) for each UFParamListElement to obtain a pointer to each parameter from the parameter block:

FirstParam = GetParam (ParamBlock, 1);

SecondParam = GetParam (ParamBlock, 2);

The actual value is stored in the Parameter member of the UFParamListElement according to the type of data it contains. The Parameter member is a UFParamUnion type (a union data type holding a value according to the type of data expected). Since both of the parameters are of type String, you can obtain the actual parameter value for each UFParamListElement by using the following notation:

FirstParam->Parameter.ParamString

SecondParam->Parameter.ParamString

If, on the other hand, the second parameter contained a numeric value, you could use this notation:

SecondParam->Parameter.ParamNumber

Study the UFParamUnion union definition in the UFDLL.H file for a complete list of all possible parameter types and how to obtain a value from them.


Picture Function - a sample UFL function

Here is a complete commented private C code module implementing the Picture function. Use this as a guide for how to create your own functions in UFLs:

/********************************

** UFLSAMP.C

**

** Private C code module

** implementing the Picture UDF.

********************************/

#include <Windows.h>

#include "UFDll.h"

#include "UFMain.h"

#include "UFUser.h"

#define PicturePlaceholder 'x'

/* UDF PROTOTYPE */

ExternC UFError FAR _export PASCAL Picture

    (UFParamBlock * ParamBlock);

/*****

*  This array gives the program the types for the

*  parameters to the UDF, the return

*  type, and the name. It also passes the

*  address of the actual function code.

*****/

UFFunctionDefStrings FunctionDefStrings [] =

{

    {"String Picture (String, String)",

     Picture},

    {NULL, NULL, NULL}

};

/*****

*  The following is the template the program

*  will insert into the Formula Editor

*  Formula text box when this function is

*  selected.

*****/

UFFunctionTemplates FunctionTemplates [] =

{

    {"Picture (!,"},

    {NULL}

};

/*****

* The following is an example of the format

* for this function. This text will appear

* in the Functions list box of the Formula

* Editor.

*****/

UFFunctionExamples FunctionExamples [] =

{

    {"\tPicture (string, picture)"},

    {NULL}

};

/*****

*  This array contains ASCII string

*  representations of the errors which

*  could occur.

*****/

char *ErrorTable [] =
{

    "no error"

};

/* Called for on initialization */

void InitForJob (UFTInt32u jobID)

{

}

/* Called on termination */

void TermForJob (UFTInt32u jobID)

{

}

l/*****

*  This function is used by the Picture UDF to

*  copy the contents of a source string and a

*  format string into a destination string.

*****/

static void copyUsingPicture    (char *dest,

const char *source, const char *picture)

{

    while (*picture != '\0')

    {

        If (tolower (*picture) ==

         PicturePlaceholder)

            If (*source != '\0')

                *dest++ = *source++;

            Else

            ; // do not insert anything

        Else

            *dest++ = *picture;

        picture++;

    }

     // copy the rest of the source

    lstrcpy (dest, source);

}

/*****

*    This is the User-Defined Function

*****/

ExternC UFError FAR _export PASCAL Picture

    (UFParamBlock * ParamBlock)

{

    UFParamListElement    *FirstParam,*SecondParam;

    FirstParam  = GetParam (ParamBlock, 1);

    SecondParam = GetParam (ParamBlock, 2);

    If (FirstParam == NULL || SecondParam ==

     NULL)

        return UFNotEnoughParameters;

    copyUsingPicture    (ParamBlock-

    ReturnValue.ReturnString,

    FirstParam-Parameter.ParamString,

    SecondParam-Parameter.ParamString);

    return UFNoError;

}


Module Definition (.def) File

The last element of your UFL is the module definition (.def) file. This is just like any module definition file you would create for a DLL, but you must make sure to explicitly export not only your UFL function, but also the specialized UFL functions defined in UFMAIN.C that Crystal Reports expects to find. The following is an example of a module definition file for the UFL that exports the Picture function (seePicture Function - a sample UFL function):

Library        UFLSAMP

Description        'User Function Library for Crystal Reports'

ExeType        Windows

HeapSize        1024

Code            Moveable Discardable Preload

Data            Moveable Preload

Segments        _TEXT    Preload

Exports

            WEP

            UFINITIALIZE

            UFTERMINATE

            UFGETVERSION

            UFSTARTJOB

            UFENDJOB

            UFGETFUNCTIONDEFSTRINGS

            UFGETFUNCTIONEXAMPLES

            UFGETFUNCTIONTEMPLATES

            UFERRORRECOVERY

            PICTURE

Notice that the only function exported that you actually coded is the Picture UFL. The rest of the exported functions have been defined for you in UFMAIN.C. Every UFL must export these 9 UF* functions. In addition to these functions, every UFL that you create must be exported.

Note: If you are creating a 32-bit UFL, do not export the WEP procedure function. If you are creating a 32-bit UFL, you will only need to include the LIBRARY, DESCRIPTION, and EXPORTS sections of the .def file.

When you have finished coding the module definition file, save it to your working directory and add it to the list of files in your project file.

Finally, compile and link the ufl* or u2l* project file. Resolve any errors that occur, and recompile if necessary. Once you have your DLL (ufl*.dll or u2l*.dll), place it in the directory that holds CRW.EXE. From that point on, when you open the Formula Editor, your User-Defined Function(s) will appear in the "Additional Functions" section at the bottom of the Functions list of the Formula Editor. Enter each function in one or more formulas, and test and modify it until it works the way you want.

Note: For additional information, review UFLSAMP1.C and UFLSAMP2.C (sample files that were installed in the Crystal Reports directory, \CRW, by default).


UFJOB Modules

Two optional modules, UFJOB.C and UFJOB.H have been provided with Crystal Reports. These files provide an implementation of theInitForJob Function, and TermForJob Function, which allow you to obtain an ID number that is specific to the current print job in Crystal Reports. At the same time, these modules establish a JobInfo structure for the current job where you can store information regarding the job. If your UFL, for example, must evaluate all values in a field before printing a result, it can tally data in the JobInfo structure until it has a result. Data can even be passed between functions using the JobInfo structure.

Use the JobInfo structure whenever you want to create UFL functions that summarize or group report data. For example, statistical functions that evaluate the median, mean, or range of values in a field can store data in the JobInfo structure.

The UFLSAMP2.C file, included with Crystal Reports, demonstrate UFLs that group data according to the Top N values. (Crystal Reports can do this automatically for you, but the functions in UFLSAMP2.C will help you understand how to use the functions and the JobInfo structure in the UFJOB modules.)

If you decide to use the UFJOB modules in your own UFL, the following are required:

  • UFJOB.C
      • add UFJOB.C to your UFL project file.
      • Note: See also UFJOB.H
  • UFJOB.H
      • #include UFJOB.H in your private C code module that implements your UFL functions.
  • Implement InitJob and TermJob
      • Replace your own implementations of the InitForJob and TermForJob functions with implementations of the InitJob and TermJob functions.


UFJOB.C

This module contains implementations of the InitForJob Function, and TermForJob Function, that provide a JobInfo structure for the current job in Crystal Reports. These replace any versions of these functions that you coded in your private C module containing your UFL definitions. They also call the InitJob and TermJob functions respectively. You will implement these functions in your private C code module.

In addition, this file also defines the FindJobInfo function. Use this function in your own code whenever you need to obtain a pointer to the JobInfo structure for the current job. This function requires only the job ID number, which is stored in the JobId member of the parameter block. The following code demonstrates how to call this function:

struct JobInfo *jobInfo;

jobInfo = FindJobInfo (ParamBlock->JobId);


UFJOB.H

This module prototypes the InitForJob Function, TermForJob Function, and FindJobInfo functions that appear in UFJOB.C. It also prototypes the InitJob and TermJob functions that you must implement yourself. Most importantly, this file defines the JobInfo structure:

struct JobInfo

{

    UFTInt32u jobId;

    struct JobInfo FAR *prev;

    struct JobInfo FAR *next;

    void FAR *data;

};

The data member of this structure allows you to store a pointer to any kind of data you wish. This means you can store information for the current job that allows you to evaluate several field values before printing a result or store data from one function to be used by another function.


Implement InitJob and TermJob

If you previously implemented the InitForJob and TermForJob functions in the private C code module with your UFL function definitions, delete those functions now since they are being replaced by the functions in UFJOB.C. Now, in your private C module, define the InitJob and TermJob functions which InitForJob and TermForJob call. You can use these functions to add job initialization or job termination code to your UFL, but they can also remain blank.

Following are examples of how you might implement these functions for your own UFL:

void InitJob (struct JobInfo *jobInfo)

{

}
void TermJob (struct JobInfo *jobInfo)

{

    If (jobInfo->data != 0)

        free (jobInfo->data);

}

Once you have done all this, you can make full use of the JobInfo structure with your own UFL function code.


Creating User-Defined Functions
in Visual Basic

Crystal Reports allows you to create User Defined Functions that are recognized by the Crystal Reports Formula Editor. In this section you will find detailed information on programming User Defined Functions in Microsoft Visual Basic.

Click the appropriate link to jump to that section:

  • Overview of User-Defined Functions in Visual Basic
  • Programming User-Defined Functions in Visual Basic
  • Visual Basic and Crystal Reports
  • Sample UFL Automation Server


Overview of User-Defined Functions in Visual Basic

The Crystal Reports Formula Editor and formula language are powerful tools, enabling you to accomplish a wide variety of report-related tasks easily and efficiently. The formula language is expandable as well. That is, while it already includes a large selection of useful functions, it also comes with the ability to accept new functions that you define to meet your needs.

User-Defined Functions that are recognized by the Crystal Reports Formula Editor can be created in a Dynamic Link Library or, for 32-bit environments, in an Automation Server. This section demonstrates how to create User-Defined Functions in an Automation Server using Visual Basic. For information on how to create User-Defined Functions in a Dynamic Link Library using the C or C++ programming language, see Programming User-Defined Functions in C. For information on creating User-Defined Functions in an Automation Server using Delphi 3.0, see Programming User-Defined Functions in Delphi.


Programming User-Defined Functions in Visual Basic

The Crystal Reports Formula Editor can access User-Defined Functions through a User Function Library (UFL). A User Function Library is a specially designed Dynamic Link Library that exposes one or more functions that you create. UFLs can be designed and programmed in any language that supports the development of Windows DLLs.

The 32-bit version of Crystal Reports Professional Edition includes the User Function Library U2LCOM.DLL. This UFL is installed in your \WINDOWS\CRYSTAL directory when you install Crystal Reports and provides an interface through which you can expose User-Defined Functions in Automation Servers.

An automation server is a Dynamic Link Library or executable file that exposes its functionality to other modules and processes through the Component Object Model. For complete information on the Component Object Model (COM), refer to Microsoft documentation or the Microsoft World Wide Web site. U2LCOM.DLL is a UFL that can access any functions exposed by any Automation Servers named with a CRUFL prefix. This means that you can create an Automation Server in any language environment that supports COM, name the server with a CRUFL prefix, register the server on a system, and the Crystal Reports Formula Editor will access and make available any functions exposed by that Automation Server.

Note: You may be more familiar with Automation Servers as OLE Automation. Though the technology behind Automation Servers is the same as OLE Automation, the correct name for these servers is now simply Automation Servers.

Visual Basic, version 4.0 and later, allows you to design 32-bit Automation Servers easily. As a Visual Basic programmer, you can design custom functions for use in your reports by exposing them in ActiveX DLLs and registering the DLL on your system.

Note: Any development environment that allows the creation of COM-based Automation Servers can use the techniques similar to those described in this section. However, the code and examples shown here are based on Visual Basic.

The steps for creating automation servers in Visual Basic are slightly different, depending on the version of Visual Basic you are using.


Using Visual Basic 4.0

There are five primary steps to creating an Automation Server in Visual Basic 4.0 that exposes functions to the U2LCOM.DLL User Function Library:

  • Set Up the Main Subroutine
  • Add a Class Module to the Project
  • Add User Functions to the Class Module
  • Name the Project
  • Compile the Project as an OLE DLL


Set Up the Main Subroutine

When Visual Basic 4.0 first opens, it creates a default project and form for you. The entry point to your Automation Server DLL must be the Main subroutine. This subroutine needs to be defined in a Visual Basic Module, but cannot be defined in a Class Module.

  1. Remove the default form from your project by highlighting the form in the Project window and choosing Remove File from the File menu.
  2. To add a new Module to the project, choose Module from the Insert menu.
  3. In the Module window, add the following:
Sub Main()
End Sub

You do not need to add any code to the Main subroutine, as long as it exists in your project.


Add a Class Module to the Project

Now you must add a Class Module to your project. The Class Module will contain any User-Defined Functions that you wish to make available to the Crystal Reports Formula Editor.

  1. To create a Class Module, choose Class Module from the Insert menu. A new Class Module window appears, and the Class Module is added to the Project window.
  2. In the Properties window, set the following properties for the Class Module:
  • Instancing = 2 - Creatable MultiUse
  • Name = Any valid Class Module name
  • Public = True

Note: For complete information on these properties, refer to Visual Basic Help.

If the Properties window is not visible, select the Class Module window, then choose Properties from the View menu.


Add User Functions to the Class Module

The next step is to add the actual User-Defined Functions that you want to appear in the Crystal Reports Formula Editor. These functions are standard Visual Basic functions that you might define in any Visual Basic project. The only requirement is that the functions are declared Public.

Type in the following function:

Public Function DateToString(date1 As Date) As String

    DateToString = Format(date1, "Long Date")

End Function

Note: For complete information on how to define functions in Visual Basic, refer to your Visual Basic documentation.

The U2LCOM.DLL UFL supports most standard Visual Basic data types and arrays. For complete information on how the Crystal Reports Formula Editor interprets Visual Basic data types and arrays, see the sections Visual Basic and Crystal Reports, and Using Arrays.


Name the Project

The U2LCOM.DLL UFL will only read Public functions exposed by Automation Servers named with a CRUFL prefix. For example, CRUFLMyFunctions is a valid project name for your Automation Server.

  1. To change the name of your project in Visual Basic 4.0, choose Options from the Tools menu. The Options dialog box appears.
  2. Click the Project Tab, and change the name of the project in the Project Name text box. The name should be CRUFLxxx, where xxx is a name of your choice.
  3. While in the Options dialog box, make sure the Startup Form for the project is the Sub Main subroutine. Click OK when finished.


Compile the Project as an OLE DLL

  1. Save the Module file, the Class Module file, and the P3roject file for your project.
  2. Choose Make OLE DLL File from the File menu. Accept the default name for the DLL (your file name and location can be anything), and click OK. Visual Basic creates your Automation Server for you and registers it in your local system Registry.


Using Visual Basic 5.0

There are only four major steps to creating an Automation Server in Visual Basic 5.0. When you finish designing your Automation Server, the U2LCOM.DLL User Function Library will be able to access all of the functions that it exposes.

  • Create a New ActiveX DLL Project
  • Add User Functions to the Class Module
  • Name the Project
  • Build the DLL


Create a New ActiveX DLL Project

  1. When you first run Visual Basic 5.0, the New Project dialog box appears. If you already have Visual Basic open, simply choose New Project from the File menu.
  2. Double-click the ActiveX DLL icon in the New Project dialog box. Visual Basic creates a new project for you with a single Class Module.

Note: For complete information on creating an ActiveX DLL in Visual Basic 5.0, refer to your Visual Basic documentation.


Add User Functions to the Class Module

The next step is to add the actual User-Defined Functions that you want to appear in the Crystal Reports Formula Editor. These functions are standard Visual Basic functions that you might define in any Visual Basic project. The only requirement is that the functions are declared Public.

Type in the following function:

Public Function DateToString(date1 As Date) As String

    DateToString = Format(date1, "Long Date")

End Function

The U2LCOM.DLL UFL supports most standard Visual Basic data types and arrays. For complete information on how the Crystal Reports Formula Editor interprets Visual Basic data types and arrays, see the sections Visual Basic and Crystal Reports, and Using Arrays.


Name the Project

The U2LCOM.DLL UFL will only read Public functions exposed by Automation Servers named with a CRUFL prefix. For example, CRUFLMyFunctions is a valid project name for your Automation Server.

To change the name of your project in Visual Basic 5.0, highlight your project in the Project window, then change its (Name) property in the Properties window to CRUFLxxx, where xxx is a name of your choice.


Build the DLL

From the File menu, choose Make CRUFLxxx.dll. Once again, xxx is the name you chose. When this command executes, Visual Basic will compile your project into an ActiveX DLL (an Automation Server) and register it in your local system Registry.


Registration of the Automation Server and Distribution of the Visual Basic Project

An Automation Server must be registered on any system on which it will be used. Automation Servers are registered in the Windows 95 or Windows NT System Registry. The file can be physically stored anywhere on your hard drive because the Registry settings tell Windows where the file is located when it is needed.

When you make an ActiveX DLL project in Visual Basic 5.0 or an OLE DLL project in Visual Basic 4.0, using the Make command from the File menu, Visual Basic automatically registers the Automation Server on your system. Once registered, you can easily test and use the new User-Defined Functions from the Crystal Reports Formula Editor.

Visual Basic 4.0 also includes an easy-to-use command-line application, REGSVR32.EXE, that will handle registering an Automation Server on your system. This application is located in the \CLISVR subdirectory of the directory in which you installed Visual Basic. This application can be used from an MS-DOS prompt by simply specifying the name of the Automation Server DLL. For example:

RegSvr32.exe C:\Projects\CRUFLMyFunctions.dll

The easiest way to distribute any Visual Basic project is to use the Setup Wizard to create an installation program. In addition to making sure all necessary files are installed where appropriate, the Setup Wizard can add code to your installation to register the Automation Server in the user's system Registry.

In addition to installing and registering your Automation Server, you must also provide the U2LCOM.DLL UFL file on any system that will use the functions exposed by your Automation Server. If the system has Crystal Reports installed, then this file will already be located in the system's \WINDOWS\CRYSTAL directory.


Using the User-Defined Functions

From Crystal Reports:

  1. Create a new report and add tables to the report, or open an existing report.
  2. From the Insert menu, choose Formula Field. The Insert Field dialog box appears.
  3. Click New, and enter a name for the new formula in the Formula Name dialog box.
  4. Click OK; the Formula Editor appears.
  5. Scroll down in the Functions list box to the Additional Functions section. Locate the User Defined Function you created.

    User-Defined Function names for functions created in Automation Servers are prefixed according to the project and class name used when you created the Automation Server. For instance, if you named your project CRUFLProject, named the class Conversion, and named the function Square, the User-Defined Function would appear in the Formula Editor as ProjectConversionSquare.

  6. Double-click the User-Defined Function, and it appears in the Formula text box. Enter valid arguments for the function. For example:

    ProjectConversionSquare(5)

  7. Click Check. Make sure no errors appear in the function.
  8. Click Accept, and place the formula in your report. Preview the report and verify that the function worked correctly.

Congratulations, you just created and used a User-Defined Function.


Visual Basic and Crystal Reports

Note: 32-bit Support Only. U2LCOM.DLL is a 32-bit UFL only and, therefore, supports only 32-bit Automation Server DLLs. To create User-Defined Functions for Crystal Reports, you must have the 32-bit edition of Visual Basic 4.0 or Visual Basic 5.0 (or another 32-bit development environment that supports the creation of COM-based Automation Servers).


Variable Types

Crystal Reports will support most common Visual Basic data types provided through a User-Defined Function developed in Visual Basic. The following table shows how Crystal Reports converts the most common Visual Basic data types to data types supported by the Formula Editor:

Visual Basic Data Types | Formula Editor Data Types
Integer Long Single Double | NumberVar
Currency | CurrencyVar
Date | DateVar
Boolean | BooleanVar
String | StringVar

Note: Ranges--The range data type available in the Crystal Reports Formula Editor is not supported in COM-based User-Defined Functions.


Using Arrays

Arrays can be passed to any User Defined Function as a parameter of the function. This means that when you design your function in Visual Basic, the function can accept an array of values of any of the supported data types. However, the function cannot return an array to the Crystal Reports Formula Editor. The following Visual Basic function is an acceptable User Defined Function for Crystal Reports:

Public Function GetNthItem (sArray() As String, n As Integer) As String

    GetNthItem = sArray(n)

End Function


Reserved Names

Certain names are reserved and cannot be used as User Defined Function names. The following names are reserved by the Crystal Reports Formula Editor for special purposes:

    • UFInitialize
    • UFTerminate
    • UFStartJob
    • UFEndJob

For more explanation of these function names, see Special Purpose Functions. In addition, User-Defined Functions cannot use the same name as any of the functions exposed by the IDispatch interface used by COM:

    • QueryInterface
    • AddRef
    • Release
    • GetTypeInfoCount
    • GetTypeInfo
    • GetIDsOfNames
    • Invoke


Function Name Prefixing

To ensure a unique name when User-Defined Functions appear in the Formula Editor, Crystal Reports appends a prefix to each function name that is generated from the project and Class Module names in the original source code. The first part of the prefix is the project name without the CRUFL prefix. The rest of the function name prefix is the Class Module name.

Once the prefix for the function name is generated, all non-alphanumeric characters are removed, and the prefix is applied to the original function name. The following table illustrates this process:

Project Name: | CRUFLTestFunctions
Class Module Name: | Conversion
User Defined Function Name: | Date_To_String()
Formula Editor Function: | TestFunctionsConversionDateToString()

This function name prefixing can be turned off if you are sure that your function names will not conflict with any other function names recognized by the Formula Editor. To turn off function name prefixing:

  1. Define a Boolean property for the class called UFPrefixFunctions.
  2. Set the value of the property to False in the Initialize subroutine for the class.

    For example:

Public UFPrefixFunctions As Boolean
Private Sub Class_Initialize()

    UFPrefixFunctions = False

End Sub

Note: Function name prefixing is designed to eliminate function name conflicts. If you turn off function name prefixing and your function name conflicts with another function, you may get unpredictable results.


Passing Parameters By Reference and By Value

Arguments can be passed to User-Defined Functions written in Visual Basic either ByRef or ByVal. ByRef is the default method for Visual Basic, but both methods will work. For instance, all of the following functions are valid:

    Public Function Test1 (num1 As Integer) As Integer

    Public Function Test1 (ByRef num1 As Integer) As Integer

    Public Function Test1 (ByVal num1 As Integer) As Integer


Error Handling

If it is possible for your User Defined Function to produce an error, the Crystal Reports Formula Editor should be notified of the error. Many types of errors are automatically handled by the Formula Editor. Passing the wrong type of data to a function, for instance, will be recognized and trapped by Crystal Reports. However, if you design a function that can produce an error unique to that function, you should provide a means for reporting that error to the Formula Editor.

To send error messages to the Formula Editor, define the UFErrorText string property in your Class Module. This property should be defined Public, using code similar to this:

Public UFErrorText As String

Any time you trap for an error condition, simply set the UFErrorText property to the error text you want reported in Crystal Reports. Setting the value of this property triggers the error in Crystal Reports, and Crystal Reports displays a dialog box containing the error message that you assigned to UFErrorText.

Note: You should not use the UFErrorText property for anything other than returning errors from User-Defined Functions. The U2LCOM.DLL UFL regularly resets the value of this property, so data can be lost if stored in UFErrorText for any reason other than reporting an error.


Special Purpose Functions

You can define several special purpose functions in your Class Module in addition to the User-Defined Functions that you are creating. The Crystal Reports Formula Editor can look for and process code defined in any of the following functions:

Public Function UFInitialize () As Long
Public Function UFTerminate () As Long
Public Sub UFStartJob (job As Long)
Public Sub UFEndJob (job As Long)

Be sure to define the functions in your code exactly as they appear above. If not defined correctly, they will be ignored by Crystal Reports. These functions are completely optional when creating your Visual Basic Automation Server. They are provided to assist you with the design of your User-Defined Functions.

UFInitialize

This function is called just after the DLL is loaded into memory. Use this function to handle one-time initialization of variables.

Return a value of 0 (zero) to indicate successful initialization. Any non-zero value indicates initialization failed.

UFTerminate

This function is called just before the DLL is unloaded from memory. Use this function to clean up any allocated memory or other data before unloading the DLL.

Return a value of 0 (zero) when finished cleaning up memory.

UFStartJob

This procedure is called by Crystal Reports just before User-Defined Functions are evaluated (or reevaluated). The Crystal Reports job number is passed to the function as the only parameter. Use this function to handle any initialization on a per-job basis.

UFEndJob

This procedure is called by Crystal Reports when the current job finishes, which happens when all pages of a report have been generated, before UFStartJob is called again, or before UFTerminate is called. This function also accepts the Crystal Reports job number as its only parameter. Handle any clean-up necessary on a per-job basis using this function.


Sample UFL Automation Server

Crystal Reports includes the source code for a sample automation server that exposes a User Defined Function. The code includes a Visual Basic 4.0 project file that can be compiled in either Visual Basic 4.0 or 5.0. Use this sample as a reference for building your own Automation Server based User-Defined Functions. You can even copy the Class Module provided into your own projects as a head-start to building Automation Servers for U2LCOM.DLL.


Creating User-Defined Functions in Delphi 3.0

Crystal Reports allows you to create User Defined Functions that are recognized by the Crystal Reports Formula Editor. In this section you will find detailed information on programming User Defined Functions in Delphi.

Click the appropriate link to jump to that section:

  • Overview of User-Defined Functions in Delphi
  • Programming User-Defined Functions in Delphi
  • Delphi and Crystal Reports


Overview of User-Defined Functions in Delphi

The Crystal Reports Formula Editor and formula language are powerful tools, enabling you to do a wide variety of report-related tasks easily and efficiently. The formula language is expandable as well. That is, while it already includes a large selection of useful functions, it also comes with the ability to accept new functions that you define to meet your needs.

User Defined Functions that are recognized by the Crystal Reports Formula Editor can be created in a Dynamic Link Library or, for 32-bit environments, in an Automation Server. This section demonstrates how to create User Defined functions in an Automation Server using Borland Delphi 3.0 (and later versions). For information on how to create User Defined Functions in a Dynamic Link Library using the C or C++ programming language, see Programming User-Defined Functions in C. For information on how to create User Defined Functions in an Automation Server using Visual Basic, see Programming User-Defined Functions in Visual Basic.


Programming User-Defined Functions in Delphi

The Crystal Reports Formula Editor can access User Defined Functions through a User Function Library (UFL). A User Function Library is a specially designed Dynamic Link Library that exposes one or more functions that you create. UFLs can be designed and programmed in any language that supports the development of Windows DLLs.

The 32-bit version of Crystal Reports Professional Edition includes the User Function Library U2LCOM.DLL. This UFL is installed in your \WINDOWS\CRYSTAL directory when you install Crystal Reports and provides an interface through which you can expose User Defined Functions in Automation Servers.

An Automation Server is a Dynamic Link Library or executable file that exposes its functionality to other modules and processes through the Component Object Model. For complete information on the Component Object Model (COM), refer to Microsoft documentation or the Microsoft World Wide Web site. U2LCOM.DLL is a UFL that can access any functions exposed by any Automation Servers named with a CRUFL prefix. This means that you can create an Automation Server in any language environment that supports COM, name the server with a CRUFL prefix, register the server on a system, and the Crystal Reports Formula Editor will access and make available any functions exposed by that Automation Server.

Note: You may be more familiar with Automation Servers as OLE Automation. Though the technology behind Automation Servers is the same as OLE Automation, the correct name for these servers is now simply Automation Servers.

Delphi 3.0 allows you to design 32-bit Automation Servers easily. As a Delphi programmer, you can design custom functions for use in your reports by exposing them in an ActiveX Library and registering the library (Automation Server) on your system.


Using Delphi 3.0

Note: Version 3.0 of Delphi is required to create Automation Servers containing User Defined Functions.

There are seven primary steps to creating User Defined Functions in an automation server in Delphi 3.0:

  • Create the Project
  • Create the Automation Object
  • Add Methods to the Type Library
  • Register the Type Library
  • Create the User-Defined Functions
  • Build the Project
  • Using the User-Defined Functions


Create the Project

When Delphi first opens, it creates a default project and form for you.

  1. Choose New from the File menu.
  2. Click the ActiveX Tab in the New Items dialog box, and double-click the ActiveX Library icon. Delphi creates a default ActiveX Library for you.

    The U2LCOM.DLL UFL will only read functions exposed by Automation Servers named with a CRUFL prefix. For example, CRUFLMyFunctions is a valid project name for your Automation Server.

  3. Choose Save Project As from the File menu, and save your Delphi project. The project should be named CRUFLxxx.DPR, where xxx is a name of your choice.


Create the Automation Object

  1. Choose New from the File menu.
  2. Click the ActiveX Tab in the New Items dialog box, and double-click the Automation Object icon. The Automation Object Wizard appears.
  3. Enter a class name appropriate to the functions you will create. Make sure Instancing is set to Multiple Instance, and click OK. The Type Library Editor appears.
  4. Make sure the name of the type library for your project matches the project name you created earlier. If not, change the name of the type library to CRUFLxxx, where xxx is the name you chose.


Add Methods to the Type Library

The methods in the class you specified when you created the type library will become User Defined Functions that appear in the Crystal Reports Formula Editor.

  1. Right-click the interface for your type library. The interface name is identical to the class name you specified preceded by an I.
  2. Choose New from the menu that appears, and choose Method.

    A new method appears below the interface in the Object list pane.

  3. Name the method according to the function you want to create.
  4. On the Attributes Tab for the method, declare your function. For example:

function Square (Number: double): double;

Note: For complete information on how to declare functions in Delphi, refer to your Delphi documentation.

The U2LCOM.DLL UFL supports most standard Delphi data types and arrays. For complete information on how the Crystal Reports Formula Editor interprets Delphi data types and arrays, see Delphi and Crystal Reports.

Continue creating methods for all User Defined Functions you want to appear in the Crystal Reports Formula Editor.


Register the Type Library

Click Register in the Type Library Editor. Delphi creates your type library and registers it on your system. A message should appear indicating that the ActiveX automation server was successfully registered. Click OK in the message box.

Note: If the type library is not registered successfully on your system, create the type library and object methods over again. If you continue to have problems, refer to your Delphi documentation on creating type libraries.

Create the User-Defined Functions

  1. Minimize the Type Library Editor, and locate the declaration of the method you created in the your type library in the Unit1.pas unit.
  2. Enter code for the function as desired. For example:
function TConversion.Square(Number: Double): Double;

begin

result := Number * Number;

end;

Continue coding all methods that you declared for the interface.


Build the Project

Save all files in your project, and choose Build All from the Project menu. Delphi builds your automation server, and the methods you declared are now available from the Crystal Reports Formula Editor.


Using the User-Defined Functions

From Crystal Reports:

  1. Create a new report and add tables to the report, or open an existing report.
  2. From the Insert menu, choose Formula Field. The Insert Field dialog box appears.
  3. Click New, and enter a name for the new formula in the Formula Name dialog box.
  4. Click OK and the Formula Editor appears.
  5. Scroll down in the Functions list box to the Additional Functions section. Locate the User-Defined Function you created.

    User-Defined Function names for functions created in Automation Servers are prefixed according to the project and class name used when you created the automation server. For instance, if you named your project CRUFLProject, named the class Conversion, and named the function Square, the User-Defined Function would appear in the Formula Editor as ProjectConversionSquare.

  6. Double-click the User-Defined Function, and it appears in the Formula text box. Enter valid arguments for the function. For example:

    ProjectConversionSquare(5)

  7. Click Check. Make sure no errors appear in the function.
  8. Click Accept, and place the formula in your report. Preview the report and verify that the function worked correctly.

Congratulations, you just created and used a User-Defined Function.


Delphi and Crystal Reports

Note: 32-bit Support Only. U2LCOM.DLL is a 32-bit UFL only and, therefore, supports only 32-bit Automation Server DLLs. To create User-Defined Functions for Crystal Reports, you must have Delphi 3.0 (or another 32-bit development environment that supports the creation of COM-based Automation Servers).

The following topics are discussed in this section:

  • Data Types.
  • Using Arrays.
  • Reserved Names.
  • Function Name Prefixing.
  • Passing Parameters By Reference and By Value.
  • Error Handling.
  • Special Purpose Functions.


Data Types

Crystal Reports will support most common Delphi data types provided through a User-Defined Function developed in Delphi 3.0. The following table shows how Crystal Reports converts the most common Delphi data types to data types supported by the Formula Editor:

Delphi Data Types | Formula Editor Data Types
ShortInt Integer LongInt Real Single Double | NumberVar
Currency | CurrencyVar
Date | DateVar
Boolean | BooleanVar
String | StringVar

Note: Ranges--The range data type available in the Crystal Reports Formula Editor is not supported in COM-based User-Defined Functions.


Using Arrays

Arrays can be passed to any User-Defined Function as a parameter of the function. This means that when you design your function in Delphi, the function can accept an array of values of any of the supported data types. However, the function cannot return an array to the Crystal Reports Formula Editor. The following Delphi function is an acceptable User-Defined Function for Crystal Reports:

Function GetNthItem (A: MyArray, n: Integer): Integer;

begin

    GetNthItem := A[n];

End;


Reserved Names

Certain names are reserved and cannot be used as User-Defined Function names. The following names are reserved by the Crystal Reports Formula Editor for special purposes:

    • UFInitialize
    • UFTerminate
    • UFStartJob
    • UFEndJob

For more explanation of these function names, see Special Purpose Functions.

In addition, User-Defined Functions cannot use the same name as any of the functions exposed by the IDispatch interface used by COM:

    • QueryInterface
    • AddRef
    • Release
    • GetTypeInfoCount
    • GetTypeInfo
    • GetIDsOfNames
    • Invoke


Function Name Prefixing

To ensure a unique name when User-Defined Functions appear in the Formula Editor, Crystal Reports appends a prefix to each function name that is generated from the project and class names. The first part of the prefix is the project name without the CRUFL prefix. The rest of the function name prefix is the class name.

Once the prefix for the function name is generated, all non-alphanumeric characters are removed, and the prefix is applied to the original function name. The following table illustrates this process:

Project Name: | CRUFLTestFunctions
Class Name: | Conversion
User Defined Function Name: | Date_To_String()
Formula Editor Function: | TestFunctionsConversionDateToString()


Passing Parameters By Reference and By Value

Arguments can be passed to User-Defined Functions written in Delphi 3.0, either by value or by reference. For instance, both of the following functions are valid:

    Function Test1 (num1: Integer): Integer;
    Function Test1 (var num1: Integer): Integer;


Error Handling

If it is possible for your User-Defined Function to produce an error, the Crystal Reports Formula Editor should be notified of the error. Many types of errors are automatically handled by the Formula Editor. Passing the wrong type of data to a function, for instance, will be recognized and trapped by Crystal Reports. However, if you design a function that can produce an error unique to that function, you should provide a means for reporting that error to the Formula Editor.

To send error messages to the Formula Editor, define the UFErrorText string property in your Class Module. This property should be defined Public, using code similar to this:

Property UFErrorText: String;

Any time you trap for an error condition, simply set the UFErrorText property to the error text you want reported in Crystal Reports. Setting the value of this property triggers the error in Crystal Reports, and Crystal Reports displays a dialog box containing the error message that you assigned to UFErrorText.

Note: You should not use the UFErrorText property for anything other than returning errors from User-Defined Functions. The U2LCOM.DLL UFL regularly resets the value of this property, so data can be lost if stored in UFErrorText for any reason other than reporting an error.


Special Purpose Functions

You can define several special purpose functions in your Class Module in addition to the User-Defined Functions that you are creating. The Crystal Reports Formula Editor can look for and process any of the following class methods:

Function UFInitialize: Integer;
Function UFTerminate: Integer;
Procedure UFStartJob (job: Integer)
Procedure UFEndJob (job: Integer)

Be sure to declare the methods in your code exactly as they appear above. If not declared correctly, they will be ignored by Crystal Reports. These methods are completely optional when creating your Delphi Automation Server. They are provided to assist you with the design of your User-Defined Functions.

UFInitialize

This function is called just after the DLL is loaded into memory. Use this function to handle one-time initialization of variables.

Returns a value of 0 (zero) to indicate successful initialization. Any non-zero value indicates initialization failed.

UFTerminate

This function is called just before the DLL is unloaded from memory. Use this function to clean up any allocated memory or other data before unloading the DLL.

Returns a value of 0 (zero) when finished cleaning up memory.

UFStartJob

This procedure is called by Crystal Reports just before User-Defined Functions are evaluated (or reevaluated). The Crystal Reports job number is passed to the function as the only parameter. Use this function to handle any initialization on a per-job basis.

UFEndJob

This procedure is called by Crystal Reports when the current job finishes, which happens when all pages of a report have been generated, before UFStartJob is called again, or before UFTerminate is called. This function also accepts the Crystal Reports job number as its only parameter. Handle any clean-up necessary on a per-job basis using this function.


Code samples for the Crystal Report Engine Automation Server

This section provides code samples using the Crystal Report Engine Automations Server. The code samples are written in Visual Basic and can be easily incorprated into your applicaion.

Click the appropriate link to jump to that section:

  • Crystal Report Engine Automation Server Sample Code in Visual Basic


Crystal Report Engine Automation Server Sample Code in Visual Basic

The following samples are listed in alphapetical order and cover the major objects, methods, and events of the Crystal Report Engine Automation Server.

Click the appropriate link to jump to that section:

  • Sample Code - Creating an Application Object
  • Sample Code - Creating a Report Object
  • Sample Code - ActivatePrintWindow Event
  • Sample Code - Area Object
  • Sample Code - CancelButtonClicked Event
  • Sample Code - Check Method
  • Sample Code - ClearError Method
  • Sample Code - CloseButtonClicked Event
  • Sample Code - ClosePrintWindow Event
  • Sample Code - Database Object
  • Sample Code - DatabaseTable Object
  • Sample Code - DatabaseTables Collection
  • Sample Code - DeactivatePrintWindow Event
  • Sample Code - DrillOnDetail Event
  • Sample Code - DrillOnGroup Event
  • Sample Code - ExportButtonClicked Event
  • Sample Code - ExportOptions Object
  • Sample Code - FieldFormat Object
  • Sample Code - FieldFormat Object
  • Sample Code - FieldObject Object
  • Sample Code - FirstPageButtonClicked Event
  • Sample Code - FormulaFieldDefinition Object
  • Sample Code - FormulaFieldDefinitions Collection
  • Sample Code - GraphObject Object
  • Sample Code - GraphObject Object
  • Sample Code - GroupTreeButtonClicked Event
  • Sample Code - LastPageButtonClicked Event
  • Sample Code - NextMagnification Method
  • Sample Code - NextPageButtonClicked Event
  • Sample Code - OpenReport Method
  • Sample Code - OpenSubreport Method
  • Sample Code - Preview Method
  • Sample Code - PrevPageButtonClicked Event
  • Sample Code - PrintButtonClicked Event
  • Sample Code - PrintOut Method
  • Sample Code - PrintSetupButtonClicked Event
  • Sample Code - ReadingRecords Event
  • Sample Code - RefreshButtonClicked Event
  • Sample Code - SearchButtonClicked Event
  • Sample Code - Section Object
  • Sample Code - SetLogOnInfo Method
  • Sample Code - ShowGroup Event
  • Sample Code - SortField Object
  • Sample Code - SQLQueryString Property
  • Sample Code - Start Event
  • Sample Code - Stop Event
  • Sample Code - SubReportObject Object
  • Sample Code - TextObject Object
  • Sample Code - View Object
  • Sample Code - Window Object
  • Sample Code - ZoomLevelChanging Event


Sample Code - Creating an Application Object

The segments of sample code below show how to create an Application Object using the Visual Basic New keyword and the CreateObject function. Two segments are shown for the New keyword. The benefits of both New keyword models are faster execution compared to CreateObject and that you can create an Application Object without having to remember the "Crystal.CRPE.Application".

Modify the following sample code to fit your needs.

  • Using the New keyword:
' Dim the object and then Set it.

' Using the New keyword with the Set statement is the recommended

' model since it allows for better error checking and debugging,

' as well as faster execution.

Dim app as CRPEAuto.Application

Set app = New Application

 Or,
' Automatically creates a new instance of the object when it is first

' referenced in the code, so it doesn't have to be set.

Dim app as New CRPEAuto.Application
  • Using the CreateObject function:
Dim crystlApplication as CRPEAuto.Application

Set crystlApplication = CreateObject("Crystal.CRPE.Application")


Sample Code - Creating a Report Object

This sample code shows how to create a Report Object. Modify the following sample code to fit your needs.

Private Sub Command1_Click()
    On Error GoTo Command1_Click_Error

    Dim crystalApplication As CRPEAuto.Application

    Dim crystalReport As CRPEAuto.Report

    Dim crystalFormFieldDefns As CRPEAuto.FormulaFieldDefinitions

    Dim crystalFormFieldDefn As CRPEAuto.FormulaFieldDefinition

    Dim strFormulaFieldName As String

    Dim strDefinitionName As String

    Dim strDefinitionText As String

    Dim boolDefinitionCheckFlag As Boolean

    Dim strFieldValueType As String

    Dim intLoopCount As Integer

    Set crystalApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalReport = crystalApplication.OpenReport _

        ("d:\crw\reports\craze\wwsales.rpt")

    Set crystalFormFieldDefns = crystalReport.FormulaFields

    'here we loop through each of the FormulaFieldDefinition records

    'pulling out the information we need on a record by record basis

    For intLoopCount = 1 To crystalFormFieldDefns.Count

        Set crystalFormFieldDefn =
crystalFormFieldDefns.Item(intLoopCount)

        strFormulaFieldName = crystalFormFieldDefn.FormulaFieldName

        strDefinitionName = crystalFormFieldDefn.Name

        strDefinitionText = crystalFormFieldDefn.Text

        boolDefinitionCheckFlag = crystalFormFieldDefn.Check

        Select Case crystalFormFieldDefn.ValueType

        'for more information on the list of ValueType values

        'please see CRFieldValueType in the VisualBasic Object Browser

            Case 7

                strFieldValueType = "Number"

            Case 8

                strFieldValueType = "Currency"

            Case 9

                strFieldValueType = "Boolean"

            Case 10

                strFieldValueType = "Date"

            Case 11

                strFieldValueType = "Time"

            Case 12

                strFieldValueType = "String"

            Case 14

                strFieldValueType = "PersistentMemo"

            Case 15

                strFieldValueType = "BLOB"

            Case Else

                strFieldValueType = "Unknown"

        End Select

        Debug.Print "************************************************"

        Debug.Print "FormulaDefinition(" + Format(intLoopCount) + ")"

        Debug.Print "   FormulaFieldName<" + strFormulaFieldName + ">"

        Debug.Print "   Name<" + strDefinitionName + ">"

        Debug.Print "   Text<" + strDefinitionText + ">"

        Debug.Print "   Check<" + Format(boolDefinitionCheckFlag) + ">"

        Debug.Print "   ValueType<" + strFieldValueType + ">"

    Next intLoopCount

Command1_Click_Exit:

    Exit Sub

Command1_Click_Error

    If crystalApplication Is Nothing Then

        MsgBox "Unable to CreateObject(""Crystal.CRPE.Application"")"

        GoTo Command1_Click_Exit

    End If

    If crystalReport Is Nothing Then

        MsgBox "Unable to
OpenReport(""d:\crw\reports\craze\wwsales.rpt"")"

        GoTo Command1_Click_Exit

    End If

    MsgBox "Unknown error in Command1_Click routine"

    GoTo Command1_Click_Exit

End Sub


Sample Code - ActivatePrintWindow Event

This sample code shows the use of the ActivatePrintWindow Event (Window Object). Modify the following sample code to fit your needs.

Option Explicit

Public WithEvents windowEvs As Window

Private Sub ActivatePrintWindow_Click()

'Starts up report window for window event ActivatePrintWindow

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport(SimpleReport)

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.ActivatePrintWindowEventEnabled & _

    Chr(13) & Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.ActivatePrintWindowEventEnabled = False

        MsgBox "Check event does not occur when print window activated"

    Else

        rpt.EventInfo.ActivatePrintWindowEventEnabled = True

        MsgBox "Check event occurs when print window activated. _

        Switch between this form and report window and _

        window should be activated/deactivated"

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

    WinText.Visible = True

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & _

        crsApp.LastErrorCode & "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & rpt.LastErrorCode & "-
>" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub


Sample Code - Area Object

This sample code shows the use of Area Object. Modify the following sample code to fit your needs.

Private Sub Command1_Click()

    On Error GoTo Command1_Click_Error

    Dim crystalApplication As CRPEAuto.Application

    Dim crystalReport As CRPEAuto.Report

    Dim crystalArea As CRPEAuto.Area

    Dim intAreaKind As Integer

    Dim strAreaDescription As String

    Set crystalApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalReport = crystalApplication.OpenReport _

    ("d:\crw\reports\craze\wwsales.rpt")

    Set crystalArea = crystalReport.Areas.Item(1)

    intAreaKind = crystalArea.Kind

    Select Case intAreaKind

        Case 1

            strAreaDescription = "ReportHeader"

        Case 2

            strAreaDescription = "PageHeader"

        Case 3

            strAreaDescription = "Group Header"

        Case 4

            strAreaDescription = "Detail"

        Case 5

            strAreaDescription = "GroupFooter"

        Case 7

            strAreaDescription = "PageFooter"

        Case 8

            strAreaDescription = "ReportFooter"

        Case Default

            strAreaDescription = "Unknown area."

    End Select

    MsgBox "Crystal Area Kind is <" + strAreaDescription + ">"

Command1_Click_Exit:

    Exit Sub

Command1_Click_Error:

  If crystalApplication Is Nothing Then

      MsgBox "Unable to CreateObject(""Crystal.CRPE.Application"")"

      GoTo Command1_Click_Exit

  End If

  If crystalReport Is Nothing Then

      MsgBox "Unable to
OpenReport(""d:\crw\reports\craze\wwsales.rpt"")"

      GoTo Command1_Click_Exit

  End If

  MsgBox "Unknown error in Command1_Click routine"

  GoTo Command1_Click_Exit

End Sub


Sample Code - CancelButtonClicked Event

This sample code shows the use of the CancelButtonClicked Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub CancelButtonClicked_Click()

'Starts up report window for window event CancelButtonClicked

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.PrintWindowButtonEventEnabled & _

    Chr(13) & Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.PrintWindowButtonEventEnabled = False

        MsgBox "Check event does not occur when cancel button clicked"

    Else

        rpt.EventInfo.PrintWindowButtonEventEnabled = True

        test = MsgBox("Check event occurs when cancel button clicked" & _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & crsApp.LastErrorCode &
_

        "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & rpt.LastErrorCode & _

        "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub


Sample Code - Check Method

This sample code shows the use of the Check Method (FormulaFieldDefinition Object). Modify the following sample code to fit your needs.

Private Sub Command1_Click()

On Error GoTo Command1_Click_Error

    Dim crystalApplication As CRPEAuto.Application

    Dim crystalReport As CRPEAuto.Report

    Dim crystalFormFieldDefns As CRPEAuto.FormulaFieldDefinitions

    Dim crystalFormFieldDefn As CRPEAuto.FormulaFieldDefinition

    Dim strFormulaFieldName As String

    Dim strDefinitionName As String

    Dim strDefinitionText As String

    Dim boolDefinitionCheckFlag As Boolean

    Dim strFieldValueType As String

    Dim intLoopCount As Integer

    Set crystalApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalReport = crystalApplication.OpenReport _

    ("d:\crw\reports\craze\wwsales.rpt")

    'NOTE : AT THIS POINT IT APPEARS THAT IN THE FOLLOWING YOU MUST USE

    ' .FormulaFields INSTEAD OF THE DOCUMENTED .FormulaFieldDefinitions

    Set crystalFormFieldDefns = crystalReport.FormulaFields

    'here we loop through each of the FormulaFieldDefinition records

    'pulling out the information we need on a record by record basis

    For intLoopCount = 1 To crystalFormFieldDefns.Count

        Set crystalFormFieldDefn =
crystalFormFieldDefns.Item(intLoopCount)

        strFormulaFieldName = crystalFormFieldDefn.FormulaFieldName

        strDefinitionName = crystalFormFieldDefn.Name

        strDefinitionText = crystalFormFieldDefn.Text

        boolDefinitionCheckFlag = crystalFormFieldDefn.Check

        Select Case crystalFormFieldDefn.ValueType

        'for more information on the list of ValueType values

        'please see CRFieldValueType in the VisualBasic Object Browser

            Case 7

                strFieldValueType = "Number"

            Case 8

                strFieldValueType = "Currency"

            Case 9

                strFieldValueType = "Boolean"

            Case 10

                strFieldValueType = "Date"

            Case 11

                strFieldValueType = "Time"

            Case 12

                strFieldValueType = "String"

            Case 14

                strFieldValueType = "PersistentMemo"

            Case 15

                strFieldValueType = "BLOB"

            Case Else

                strFieldValueType = "Unknown"

        End Select

        Debug.Print "************************************************"

        Debug.Print "FormulaDefinition(" + Format(intLoopCount) + ")"

        Debug.Print "   FormulaFieldName<" + strFormulaFieldName + ">"

        Debug.Print "   Name<" + strDefinitionName + ">"

        Debug.Print "   Text<" + strDefinitionText + ">"

        Debug.Print "   Check<" + Format(boolDefinitionCheckFlag) + ">"

        Debug.Print "   ValueType<" + strFieldValueType + ">"

    Next intLoopCount

Command1_Click_Exit:

    Exit Sub

Command1_Click_Error:

  If crystalApplication Is Nothing Then

      MsgBox "Unable to CreateObject(""Crystal.CRPE.Application"")"

      GoTo Command1_Click_Exit

  End If

  If crystalReport Is Nothing Then

      MsgBox "Unable to
OpenReport(""d:\crw\reports\craze\wwsales.rpt"")"

      GoTo Command1_Click_Exit

  End If

  MsgBox "Unknown error in Command1_Click routine"

  GoTo Command1_Click_Exit

End Sub


Sample Code - ClearError Method

This sample code shows the use of the ClearError Method (Report Object). Modify the following sample code to fit your needs.

Dim crystlApplication As CRPEAuto.Application

     Dim crystlReport As CRPEAuto.Report

     Dim test As Index

Private Sub Command1_Click()

    Set crystlApplication = CreateObject("Crystal.CRPE.Application")

    Set crystlReport = crystlApplication.OpenReport _

    ("c:\crw\reports\xtreme\wwsales.rpt")

  ClearError

End Sub

Sub ClearError()

    If crystlReport.LastErrorCode <> 0 Then

        MsgBox test & ". Unexpected report error: " & _

        crystlReport.LastErrorCode & "->" & crystlReport.LastErrorString

    End If

    Call ResetErr

    crystlReport.ClearError

    Resume Next

End Sub


Sample Code - CloseButtonClicked Event

This sample code shows the use of the CloseButtonClicked Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub CloseButtonClicked_Click()

'Starts up report window for window event CloseButtonClicked

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    rpt.PrintWindowOptions.CanDrillDown = True

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.PrintWindowButtonEventEnabled & _

    Chr(13) & Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.PrintWindowButtonEventEnabled = False

        MsgBox "Check event does not occur when close button clicked"

    Else

        rpt.EventInfo.PrintWindowButtonEventEnabled = True

        test = MsgBox("Check event occurs when close drill down _

        view button clicked (drill down on group to enable it)" & _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

Private Sub windowEvs_CloseButtonClicked(ByVal ViewIndex As Integer,
useDefault As Boolean)

'executed when close button clicked - test using default and _

'not using default behaviour

    If def Then

    'test for default behaviour:

        MsgBox "Window CloseButtonClicked event" & Chr(13) & Chr(13) & _

        "Parameters:" & Chr(13) & "ViewIndex: " & ViewIndex & _

        Chr(13) & "useDefault: " & useDefault & Chr(13) & Chr(13) & _

        "Drill down view should now close"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window CloseButtonClicked event" & Chr(13) & Chr(13) & _

        "Parameters:" & Chr(13) & "ViewIndex: " & ViewIndex & _

        Chr(13) & "useDefault: " & useDefault & Chr(13) & Chr(13) & _

        "Drill down view should NOT close"

    End If

End Sub


Sample Code - ClosePrintWindow Event

This sample code shows the use of the ClosePrintWindow Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub ClosePrintWindow_Click()

'Starts up report window for window event ClosePrintWindow

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.ClosePrintWindowEventEnabled & Chr(13) & _

    Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.ClosePrintWindowEventEnabled = False

        MsgBox "Check event does not occur when window closed"

    Else

        rpt.EventInfo.ClosePrintWindowEventEnabled = True

        test = MsgBox("Check event occurs when window closed" & _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & crsApp.LastErrorCode &
_

        "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & rpt.LastErrorCode & _

        "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub windowEvs_ClosePrintWindow(useDefault As Boolean)

'executed when window is closed - test using default and not _

'using default behaviour

    If def Then

    'test for default behaviour:

        MsgBox "Window ClosePrintWindow event" & Chr(13) & Chr(13) & _

        "Parameters:" & Chr(13) & "useDefault: " & useDefault & _

        Chr(13) & Chr(13) & "Window should now close"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window ClosePrintWindow event" & Chr(13) & Chr(13) & _

        "Parameters:" & Chr(13) & "useDefault: " & useDefault & _

        Chr(13) & Chr(13) & "Window should NOT close"

    End If

    WinText.Visible = False

End Sub


Sample Code - Database Object

This sample code shows the use of the Database Object. Modify the following sample code to fit your needs.

Private Sub Command1_Click()

    On Error GoTo Command1_Click_Error

    Dim crystalApplication As CRPEAuto.Application

    Dim crystalReport As CRPEAuto.Report

    Dim db As CRPEAuto.Database

    Dim dbtable As CRPEAuto.DatabaseTables

    Set crystalApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalReport = crystalApplication.OpenReport _

    ("d:\crw\reports\craze\wwsales.rpt")

    Set db = crystalReport.Database

    Set dbtable = db.Tables

    MsgBox "Number of tables : " & dbtable.Count

Command1_Click_Exit:

    Exit Sub

Command1_Click_Error:

  If crystalApplication Is Nothing Then

      MsgBox "Unable to CreateObject(""Crystal.CRPE.Application"")"

      GoTo Command1_Click_Exit

  End If

  If crystalReport Is Nothing Then

      MsgBox "Unable to
OpenReport(""d:\crw\reports\craze\wwsales.rpt"")"

      GoTo Command1_Click_Exit

  End If

  MsgBox "Unknown error in Command1_Click routine"

  GoTo Command1_Click_Exit

End Sub


Sample Code - DatabaseTable Object

This sample code shows the use of DatabaseTable Object. Modify the following sample code to fit your needs.

Private Sub Command1_Click()

    On Error GoTo Command1_Click_Error

    Dim crystalApplication As CRPEAuto.Application

    Dim crystalReport As CRPEAuto.Report

    Dim db As CRPEAuto.Database

    Dim dbtables As CRPEAuto.DatabaseTables

    Dim dbTable As CRPEAuto.DatabaseTable

    Dim dbFields As CRPEAuto.DatabaseFieldDefinitions

    Dim dbField As CRPEAuto.DatabaseFieldDefinition

    Set crystalApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalReport = crystalApplication.OpenReport _

    ("d:\crw\reports\craze\wwsales.rpt")

    Set db = crystalReport.Database

    Set dbtables = db.Tables

    'find the alias name of the first table in the database

    If dbtables.Count >= 1 Then

        Set dbTable = dbtables.Item(1)

        Set dbFields = dbTable.Fields

      Set dbField = dbFields.Item(1)

      MsgBox "Table Alias Name is <" + dbField.TableAliasName + ">"

    End If

Command1_Click_Exit:

    Exit Sub

Command1_Click_Error:

  If crystalApplication Is Nothing Then

      MsgBox "Unable to CreateObject(""Crystal.CRPE.Application"")"

      GoTo Command1_Click_Exit

  End If

  If crystalReport Is Nothing Then

      MsgBox "Unable to
OpenReport(""d:\crw\reports\craze\wwsales.rpt"")"

      GoTo Command1_Click_Exit

  End If

  MsgBox "Unknown error in Command1_Click routine"

  GoTo Command1_Click_Exit

End Sub


Sample Code - DatabaseTables Collection

This sample code shows the use of DatabaseTables Collection. Modify the following sample code to fit your needs.

Private Sub Command1_Click()

    On Error GoTo Command1_Click_Error

    Dim crystalApplication As CRPEAuto.Application

    Dim crystalReport As CRPEAuto.Report

    Dim db As CRPEAuto.Database

    Dim dbtables As CRPEAuto.DatabaseTables

    Dim dbTable as CRPEAuto.DatabaseTable

    Set crystalApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalReport = crystalApplication.OpenReport _

    ("d:\crw\reports\craze\wwsales.rpt")

    Set db = crystalReport.Database

    Set dbtables = db.Tables

    MsgBox "Number of tables : " & dbtables.Count

Command1_Click_Exit:

    Exit Sub

Command1_Click_Error:

  If crystalApplication Is Nothing Then

      MsgBox "Unable to CreateObject(""Crystal.CRPE.Application"")"

      GoTo Command1_Click_Exit

  End If

  If crystalReport Is Nothing Then

      MsgBox "Unable to
OpenReport(""d:\crw\reports\craze\wwsales.rpt"")"

      GoTo Command1_Click_Exit

  End If

  MsgBox "Unknown error in Command1_Click routine"

GoTo Command1_Click_Exit

End Sub


Sample Code - DeactivatePrintWindow Event

This sample code shows the use of the DeactivatePrintWindow Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub DeactivatePrintWindow_Click()

'Starts up report window for window event DeactivatePrintWindow

On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.ActivatePrintWindowEventEnabled & _

    Chr(13) & Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.ActivatePrintWindowEventEnabled = False

        MsgBox "Check event does not occur when print window deactivated"

    Else

        rpt.EventInfo.ActivatePrintWindowEventEnabled = True

        MsgBox "Check event occurs when print window deactivated. Switch
between this form and report window and window should be activated/
deactivated"

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

    WinText.Visible = True

Exit Sub        ' Exit to avoid handler.

Private Sub windowEvs_DeactivatePrintWindow()

'executed when window is deactivated(loses focus)

    dcount = dcount + 1

    WinText.Text = "Window DeactivatePrintWindow event. " & "Count: " &
dcount

End Sub


Sample Code - DrillOnDetail Event

This sample code shows the use of the DrillOnDetail Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub DrillOnDetail_Click()

'Starts up report window for window event DrillOnGroup

On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    rpt.PrintWindowOptions.CanDrillDown = True

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.GroupEventEnabled & Chr(13) & Chr(13) & _

    "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.GroupEventEnabled = False

        MsgBox "Check event does not occur when double click _

        on report detail field"

    Else

        rpt.EventInfo.GroupEventEnabled = True

        'has useDefault but there is no default behaviour

        MsgBox "Check event occurs when double click on report detail
field"

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & crsApp.LastErrorCode &
_

        "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & rpt.LastErrorCode & _

        "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub windowEvs_DrillOnDetail(ByVal FieldValues As Variant, _

    ByVal SelectedFieldIndex As Long, useDefault As Boolean)

'executed when drill on detail - test using default and _

'not using default behaviour

Dim x As Integer

    For x = LBound(FieldValues) To UBound(FieldValues)

        MsgBox "FieldValue" & x & " name: " & FieldValues(x).Name & _

        Chr(13) & "FieldValue" & x & " value: " & FieldValues(x).Value

    Next x

    MsgBox "Window DrillOnDetail event" & Chr(13) & Chr(13) & _

    "Parameters:" & Chr(13) & "Selected FieldValue name: " & _

    FieldValues(SelectedFieldIndex).Name & Chr(13) & _

    "Selected FieldValue value: " &
FieldValues(SelectedFieldIndex).Value & _

    Chr(13) & "SelectedFieldIndex: " & SelectedFieldIndex & Chr(13) & _

    "useDefault: " & useDefault

End Sub


Sample Code - DrillOnGroup Event

This sample code shows the use of the DrillOnGroup Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub DrillOnGroup_Click()

'Starts up report window for window event DrillOnGroup

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    rpt.PrintWindowOptions.CanDrillDown = True

    rpt.PrintWindowOptions.HasGroupTree = True

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.GroupEventEnabled & Chr(13) & Chr(13) & _

    "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.GroupEventEnabled = False

        MsgBox "Check event does not occur when drill on a group/graph/
grouptree"

   Else

        rpt.EventInfo.GroupEventEnabled = True

        test = MsgBox("Check event occurs when drill on a _

        group/graph/grouptree" & Chr(13) & Chr(13) & _

        "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & crsApp.LastErrorCode &
_

        "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & rpt.LastErrorCode & _

        "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub windowEvs_DrillOnGroup(ByVal GroupNameList As Variant, _

    ByVal DrillType As CRPEAuto.CRDrillType, useDefault As Boolean)

'executed when drill on group - test using default and _

'not using default behaviour

Dim x As Integer

    For x = LBound(GroupNameList) To UBound(GroupNameList)

        MsgBox "GroupName" & x & ": " & GroupNameList(x)

    Next x

    If def Then

        'test for default behaviour:

        MsgBox "Window DrillOnGroup event" & Chr(13) & Chr(13) & _

        "Parameters:" & Chr(13) & "GroupNameList: " & _

        GroupNameList(UBound(GroupNameList)) & Chr(13) & _

        "DrillType(on group=0;on grouptree=1;on graph=2): " & _

        DrillType & Chr(13) & "useDefault: " & useDefault & _

        Chr(13) & Chr(13) & "Drill down should occur"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window DrillOnGroup event" & Chr(13) & Chr(13) & _

        "Parameters:" & Chr(13) & "GroupNameList: " & _

        GroupNameList(UBound(GroupNameList)) & Chr(13) &

        "DrillType(on group=0;on grouptree=1;on graph=2): " & _

        DrillType & Chr(13) & "useDefault: " & useDefault & _

        Chr(13) & Chr(13) & "Drill down should NOT occur"

    End If

End Sub


Sample Code - ExportButtonClicked Event

This sample code shows the use of the ExportButtonClicked Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub ExportButtonClicked_Click()

'Starts up report window for window event ExportButtonClicked

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.PrintWindowButtonEventEnabled & _

    Chr(13) & Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.PrintWindowButtonEventEnabled = False

        MsgBox "Check event does not occur when export button clicked"

    Else

        rpt.EventInfo.PrintWindowButtonEventEnabled = True

        test = MsgBox("Check event occurs when export button clicked" & _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & crsApp.LastErrorCode &
_

        "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & rpt.LastErrorCode & _

        "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub windowEvs_ExportButtonClicked(useDefault As Boolean)

'executed when export button clicked - test using default and _

'not using default behaviour

    If def Then

    'test for default behaviour:

        MsgBox "Window ExportButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Export dialog should appear"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window ExportButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Export dialog should NOT
appear"

    End If

End Sub


Sample Code - ExportOptions Object

This sample code shows the use of the ExportOptions Object. Modify the following sample code to fit your needs.

Private Sub Command1_Click()

    On Error GoTo Command1_Click_Error

    Dim crystalApplication As CRPEAuto.Application

    Dim crystalReport As CRPEAuto.Report

    Dim crystalExportOptions As CRPEAuto.ExportOptions

    Set crystalApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalReport = crystalApplication.OpenReport _

    ("d:\crw\reports\craze\wwsales.rpt")

    MsgBox "Export using prompt"

    'We will be prompted for one of the nearly 40 formats

    'as well as the destination, delimiter and numerous other values

    'because in this first example we have to define all of

    'the ExportOptions at run time

    Call crystalReport.Export(True)

    'and then we do it by setting the export options

    Set crystalExportOptions = crystalReport.ExportOptions

    crystalExportOptions.CharFieldDelimiter = ","

    crystalExportOptions.CharStringDelimiter = "'"

    crystalExportOptions.DiskFileName = "Test.tst"

    crystalExportOptions.UseReportDateFormat = True

    crystalExportOptions.HTMLFileName = "TestHTML.htm"

    crystalExportOptions.FormatType = 3

    '  0=no format, 1=crystal report, 2=data interchange,

    '  3=html, 4=richtext, ... 14=word for windows, and lots of others

    '  look for CRExportFormatType in the Object Browser

    crystalExportOptions.UseReportNumberFormat = True

    crystalExportOptions.DestinationType = 1

    ' 0=no destination,1=diskfile,2=mapi,3=mailVIM,4=MicrosoftExchange

    ' found under CRExportDestinationType in the Object Browser

    Call crystalReport.Export(False)

Command1_Click_Exit:

    Exit Sub

Command1_Click_Error:

  If crystalApplication Is Nothing Then

      MsgBox "Unable to CreateObject(""Crystal.CRPE.Application"")"

      GoTo Command1_Click_Exit

  End If

  If crystalReport Is Nothing Then

      MsgBox "Unable to
OpenReport(""d:\crw\reports\craze\wwsales.rpt"")"

      GoTo Command1_Click_Exit

  End If

  MsgBox "Unknown error in Command1_Click routine"

  GoTo Command1_Click_Exit

End Sub


Sample Code - FieldFormat Object

This sample code shows the use of FieldObject Object. Modify the following sample code to fit your needs.

Private Sub Command1_Click()

    On Error GoTo Command1_Click_Error

    Dim crystalApplication As CRPEAuto.Application

    Dim crystalReport As CRPEAuto.Report

    Dim crystalArea As CRPEAuto.Area

    Dim crystalSection As CRPEAuto.Section

    Dim lngSectionHeight As Long

    Dim lngSectionWidth As Long

    Set crystalApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalReport = crystalApplication.OpenReport _

    ("d:\crw\reports\craze\wwsales.rpt")

    Set crystalArea = crystalReport.Areas.Item(1)

    Set crystalSection = crystalArea.Sections(1)

    lngSectionHeight = crystalSection.Height

    lngSectionWidth = crystalSection.Width

    MsgBox "In twips the Crystal section is " + _

    Format(lngSectionHeight, "######") + " x " + _

    Format(lngSectionWidth, "######")

    Set crystalReport = Nothing

    Set crystalArea = Nothing

    Set crystalSection = Nothing

    Kill "d:\crw\reports\xtreme\wwsales.rpt"

Command1_Click_Exit:

    Exit Sub

Command1_Click_Error:

  If crystalApplication Is Nothing Then

      MsgBox "Unable to CreateObject(""Crystal.CRPE.Application"")"

      GoTo Command1_Click_Exit

  End If

  If crystalReport Is Nothing Then

      MsgBox "Unable to
OpenReport(""d:\crw\reports\craze\wwsales.rpt"")"

      GoTo Command1_Click_Exit

  End If

  MsgBox "Unknown error in Command1_Click routine"

  GoTo Command1_Click_Exit

End Sub


Sample Code - FieldObject Object

This sample code shows the use of the FieldObject Object. Modify the following sample code to fit your needs.

Private Sub Command1_Click()

    On Error GoTo Command1_Click_Error

    Dim crystalApplication As CRPEAuto.Application

    Dim crystalReport As CRPEAuto.Report

    Dim crystalFieldObject as CRPEAuto.FieldObject

    Set crystalApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalReport = crystalApplication.OpenReport _

    ("d:\crw\reports\craze\wwsales.rpt")

    ' field object stuff, but who is the parent

Command1_Click_Exit:

    Exit Sub

Command1_Click_Error:

  If crystalApplication Is Nothing Then

      MsgBox "Unable to CreateObject(""Crystal.CRPE.Application"")"

      GoTo Command1_Click_Exit

  End If

  If crystalReport Is Nothing Then

      MsgBox "Unable to
OpenReport(""d:\crw\reports\craze\wwsales.rpt"")"

      GoTo Command1_Click_Exit

  End If

  MsgBox "Unknown error in Command1_Click routine"

  GoTo Command1_Click_Exit

End Sub


Sample Code - FirstPageButtonClicked Event

This sample code shows the use of the FirstPageButtonClicked Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub FirstPageButtonClicked_Click()

'Starts up report window for window event FirstPageButtonClicked

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.PrintWindowButtonEventEnabled & _

    Chr(13) & Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.PrintWindowButtonEventEnabled = False

        MsgBox "Check event does not occur when first page button
clicked"

    Else

        rpt.EventInfo.PrintWindowButtonEventEnabled = True

        test = MsgBox("Check event occurs when first page _

        button clicked" & Chr(13) & Chr(13) & "Use default _

        behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    rptView.ShowNthPage (5)

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & crsApp.LastErrorCode &
_

        "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & rpt.LastErrorCode & _

        "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub windowEvs_FirstPageButtonClicked(useDefault As Boolean)

'executed when first page button clicked - test using

'default and not using default behaviour

    If def Then

    'test for default behaviour:

        MsgBox "Window FirstPageButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Preview should go to first
page"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window FirstPageButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Preview should _

        NOT go to first page"

    End If

End Sub


Sample Code - FormulaFieldDefinition Object

This sample code shows the use of the FormulaFieldDefinition Object. Modify the following sample code to fit your needs.

Private Sub Command1_Click()

On Error GoTo Command1_Click_Error

    Dim crystalApplication As CRPEAuto.Application

    Dim crystalReport As CRPEAuto.Report

    Dim crystalFormFieldDefns As CRPEAuto.FormulaFieldDefinitions

    Dim crystalFormFieldDefn As CRPEAuto.FormulaFieldDefinition

    Dim strFormulaFieldName As String

    Dim strDefinitionName As String

    Dim strDefinitionText As String

    Dim boolDefinitionCheckFlag As Boolean

    Dim strFieldValueType As String

    Dim intLoopCount As Integer

    Set crystalApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalReport = crystalApplication.OpenReport _

    ("d:\crw\reports\craze\wwsales.rpt")

    'NOTE : AT THIS POINT IT APPEARS THAT IN THE FOLLOWING YOU MUST USE

    ' .FormulaFields INSTEAD OF THE DOCUMENTED .FormulaFieldDefinitions

    Set crystalFormFieldDefns = crystalReport.FormulaFields

    'here we loop through each of the FormulaFieldDefinition records

    'pulling out the information we need on a record by record basis

    For intLoopCount = 1 To crystalFormFieldDefns.Count

        Set crystalFormFieldDefn =
crystalFormFieldDefns.Item(intLoopCount)

        strFormulaFieldName = crystalFormFieldDefn.FormulaFieldName

        strDefinitionName = crystalFormFieldDefn.Name

        strDefinitionText = crystalFormFieldDefn.Text

        boolDefinitionCheckFlag = crystalFormFieldDefn.Check

        Select Case crystalFormFieldDefn.ValueType

        'for more information on the list of ValueType values

        'please see CRFieldValueType in the VisualBasic Object Browser

            Case 7

                strFieldValueType = "Number"

            Case 8

                strFieldValueType = "Currency"

            Case 9

                strFieldValueType = "Boolean"

            Case 10

                strFieldValueType = "Date"

            Case 11

                strFieldValueType = "Time"

            Case 12

                strFieldValueType = "String"

            Case 14

                strFieldValueType = "PersistentMemo"

            Case 15

                strFieldValueType = "BLOB"

            Case Else

                strFieldValueType = "Unknown"

        End Select

        Debug.Print "************************************************"

        Debug.Print "FormulaDefinition(" + Format(intLoopCount) + ")"

        Debug.Print "   FormulaFieldName<" + strFormulaFieldName + ">"

        Debug.Print "   Name<" + strDefinitionName + ">"

        Debug.Print "   Text<" + strDefinitionText + ">"

        Debug.Print "   Check<" + Format(boolDefinitionCheckFlag) + ">"

        Debug.Print "   ValueType<" + strFieldValueType + ">"

    Next intLoopCount

Command1_Click_Exit:

    Exit Sub

Command1_Click_Error:

  If crystalApplication Is Nothing Then

      MsgBox "Unable to CreateObject(""Crystal.CRPE.Application"")"

      GoTo Command1_Click_Exit

  End If

  If crystalReport Is Nothing Then

      MsgBox "Unable to
OpenReport(""d:\crw\reports\craze\wwsales.rpt"")"

      GoTo Command1_Click_Exit

  End If

  MsgBox "Unknown error in Command1_Click routine"

  GoTo Command1_Click_Exit

End Sub


Sample Code - FormulaFieldDefinitions Collection

This sample code shows the use of the FormulaFieldDefinitions Collection. Modify the following sample code to fit your needs.

Private Sub Command1_Click()

On Error GoTo Command1_Click_Error

    Dim crystalApplication As CRPEAuto.Application

    Dim crystalReport As CRPEAuto.Report

    Dim crystalFormFieldDefns As CRPEAuto.FormulaFieldDefinitions

    Dim crystalFormFieldDefn As CRPEAuto.FormulaFieldDefinition

    Dim strFormulaFieldName As String

    Dim strDefinitionName As String

    Dim strDefinitionText As String

    Dim boolDefinitionCheckFlag As Boolean

    Dim strFieldValueType As String

    Dim intLoopCount As Integer

    Set crystalApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalReport = crystalApplication.OpenReport _

    ("d:\crw\reports\craze\wwsales.rpt")

    'NOTE : AT THIS POINT IT APPEARS THAT IN THE FOLLOWING YOU MUST USE

    ' .FormulaFields INSTEAD OF THE DOCUMENTED .FormulaFieldDefinitions

    Set crystalFormFieldDefns = crystalReport.FormulaFields

    'here we loop through each of the FormulaFieldDefinition records

    'pulling out the information we need on a record by record basis

    For intLoopCount = 1 To crystalFormFieldDefns.Count

        Set crystalFormFieldDefn =
crystalFormFieldDefns.Item(intLoopCount)

        strFormulaFieldName = crystalFormFieldDefn.FormulaFieldName

        strDefinitionName = crystalFormFieldDefn.Name

        strDefinitionText = crystalFormFieldDefn.Text

        boolDefinitionCheckFlag = crystalFormFieldDefn.Check

        Select Case crystalFormFieldDefn.ValueType

        'for more information on the list of ValueType values

        'please see CRFieldValueType in the VisualBasic Object Browser

            Case 7

                strFieldValueType = "Number"

            Case 8

                strFieldValueType = "Currency"

            Case 9

                strFieldValueType = "Boolean"

            Case 10

                strFieldValueType = "Date"

            Case 11

                strFieldValueType = "Time"

            Case 12

                strFieldValueType = "String"

            Case 14

                strFieldValueType = "PersistentMemo"

            Case 15

                strFieldValueType = "BLOB"

            Case Else

                strFieldValueType = "Unknown"

        End Select

        Debug.Print "************************************************"

        Debug.Print "FormulaDefinition(" + Format(intLoopCount) + ")"

        Debug.Print "   FormulaFieldName<" + strFormulaFieldName + ">"

        Debug.Print "   Name<" + strDefinitionName + ">"

        Debug.Print "   Text<" + strDefinitionText + ">"

        Debug.Print "   Check<" + Format(boolDefinitionCheckFlag) + ">"

        Debug.Print "   ValueType<" + strFieldValueType + ">"

    Next intLoopCount

Command1_Click_Exit:

    Exit Sub

Command1_Click_Error:

  If crystalApplication Is Nothing Then

      MsgBox "Unable to CreateObject(""Crystal.CRPE.Application"")"

      GoTo Command1_Click_Exit

  End If

  If crystalReport Is Nothing Then

      MsgBox "Unable to
OpenReport(""d:\crw\reports\craze\wwsales.rpt"")"

      GoTo Command1_Click_Exit

  End If

  MsgBox "Unknown error in Command1_Click routine"

  GoTo Command1_Click_Exit

End Sub


Sample Code - GraphObject Object

This sample code shows the use of the GraphObject Object. Modify the following sample code to fit your needs.

Private Sub Command1_Click()

On Error GoTo Command1_Click_Error

    Dim crystalApplication As CRPEAuto.Application

    Dim crystalReport As CRPEAuto.Report

    Dim crystalSections As CRPEAuto.Sections

    Dim crystalSection As CRPEAuto.Section

    Dim crystalReportObjects As CRPEAuto.ReportObjects

    Dim crystalGraphObject As CRPEAuto.GraphObject

    Dim intSectionCount As Integer

    Dim intReportObjectCount As Integer

    Dim intObjectFound As Integer

    Dim strTitle As String

    Dim strGraphDisplayType As String

    Set crystalApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalReport = crystalApplication.OpenReport _

    ("d:\crw\reports\craze\wwsales.rpt")

    Set crystalSections = crystalReport.Sections

    intObjectFound = False

    intSectionCount = 1

    While Not (intObjectFound) And _

          intSectionCount <= crystalSections.Count

      Set crystalSection = crystalSections.Item(intSectionCount)

      Set crystalReportObjects = crystalSection.ReportObjects

      intReportObjectCount = 1

      While Not (intObjectFound) And _

            intReportObjectCount <= crystalSection.ReportObjects.Count

        Select Case crystalReportObjects.Item(intReportObjectCount).Kind

          Case 1  'FieldObject

          Case 2  'TextObject

          Case 3  'LineObject

          Case 4  'BoxObject

          Case 5  'SubReportObject

          Case 6  'OLEObject

          Case 7  'GraphObject

              intObjectFound = True

              Set crystalGraphObject = _

           crystalReportObjects.Item(intReportObjectCount)

          Case 8  'CrossTabObject

          Case 9  'BLOBFieldObject

          Case Else

        End Select

        intReportObjectCount = intReportObjectCount + 1

      Wend 'bottom of while loop through report objects within section

      intSectionCount = intSectionCount + 1

    Wend 'bottom of while loop through sections within report

    If intObjectFound Then

        strTitle = crystalGraphObject.Title

        Select Case crystalGraphObject.DisplayType

          Case 2

                strGraphDisplayType = "StackedBar"

          Case 3

                strGraphDisplayType = "PercentBar"

          Case 4

                strGraphDisplayType = "3DSideBySideBar"

          Case 5

                strGraphDisplayType = "3DStackedBar"

          Case 6

                strGraphDisplayType = "3DPercentBar"

          Case Else

                strGraphDisplayType = "Other or Unknown"

        End Select

        Debug.Print "GraphObject.Title<" + strTitle + ">"

        Debug.Print "GraphObject.DisplayType<" + strGraphDisplayType +
">"

    End If

Command1_Click_Exit:

    Exit Sub

Command1_Click_Error:

  If crystalApplication Is Nothing Then

      MsgBox "Unable to CreateObject(""Crystal.CRPE.Application"")"

      GoTo Command1_Click_Exit

  End If

  If crystalReport Is Nothing Then

      MsgBox "Unable to
OpenReport(""d:\crw\reports\craze\wwsales.rpt"")"

      GoTo Command1_Click_Exit

  End If

  MsgBox "Unknown error in Command1_Click routine"

  GoTo Command1_Click_Exit

End Sub


Sample Code - GroupTreeButtonClicked Event

This sample code shows the use of the GroupTreeButtonClicked Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub GroupTreeButtonClicked_Click()

'Starts up report window for window event GroupTreeButtonClicked

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    rpt.PrintWindowOptions.HasGroupTree = True

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.PrintWindowButtonEventEnabled & _

    Chr(13) & Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.PrintWindowButtonEventEnabled = False

        MsgBox "Check event does not occur when group tree button
clicked"

    Else

        rpt.EventInfo.PrintWindowButtonEventEnabled = True

        test = MsgBox("Check event occurs when group tree button clicked"
& _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & crsApp.LastErrorCode &
_

        "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & rpt.LastErrorCode & _

        "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub windowEvs_GroupTreeButtonClicked(ByVal Visible As Boolean, _

                        useDefault As Boolean)

'executed when group tree button clicked

    If def Then

    'test for default behaviour:

        MsgBox "Window GroupTreeButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "Visible: " & _

        Visible & Chr(13) & "useDefault: " & useDefault & _

        Chr(13) & Chr(13) & "Preview should now show/hide group tree"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window GroupTreeButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "Visible: " & _

        Visible & Chr(13) & "useDefault: " & useDefault & _

        Chr(13) & Chr(13) & "Preview should NOT show/hide group tree"

    End If

End Sub


Sample Code - LastPageButtonClicked Event

This sample code shows the use of the LastPageButtonClicked Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer    'Required.

Private Sub LastPageButtonClicked_Click()

'Starts up report window for window event LastPageButtonClicked

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport(LongReport)

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.PrintWindowButtonEventEnabled & _

    Chr(13) & Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.PrintWindowButtonEventEnabled = False

        MsgBox "Check event does not occur when last page button clicked"

    Else

        rpt.EventInfo.PrintWindowButtonEventEnabled = True

        test = MsgBox("Check event occurs when last page button clicked"
& _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

Private Sub windowEvs_LastPageButtonClicked(useDefault As Boolean)

'executed when last page button clicked

    If def Then

    'test for default behaviour:

        MsgBox "Window LastPageButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Preview should go to last page"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window LastPageButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Preview should _

        NOT go to last page"

    End If

End Sub


Sample Code - NextMagnification Method

This sample code shows the use of the NextMagnification Method (View Object). Modify the following sample code to fit your needs.

    Dim test As Index

    Dim crwApplication As CRPEAuto.Application

    Dim crystalreport As CRPEAuto.Report

    Dim repViewObj As CRPEAuto.View

Private Sub Command1_Click()

    'shows report at next magnification zoom level

    Set crwApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalreport = crwApplication.OpenReport _

    ("c:\crw\reports\xtreme\wwsales.rpt")

    repVar = "SimpleReport"

    Set repViewObj = crystalreport.Preview

    MsgBox "Use NextMagnification to zoom preview of report"

End Sub


Sample Code - NextPageButtonClicked Event

This sample code shows the use of the NextPageButtonClicked Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub NextPageButtonClicked_Click()

'Starts up report window for window event NextPageButtonClicked

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtremme\www.sales.rpt")

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.PrintWindowButtonEventEnabled & _

    Chr(13) & Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.PrintWindowButtonEventEnabled = False

        MsgBox "Check event does not occur when next page button clicked"

    Else

        rpt.EventInfo.PrintWindowButtonEventEnabled = True

        test = MsgBox("Check event occurs when next page button clicked"
& _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & crsApp.LastErrorCode &
_

        "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & rpt.LastErrorCode & _

        "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub windowEvs_NextPageButtonClicked(useDefault As Boolean)

'executed when next page button clicked

    If def Then

    'test for default behaviour:

        MsgBox "Window NextPageButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Preview should go to next page"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window NextPageButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Preview should NOT _

        go to next page"

    End If

End Sub


Sample Code - OpenReport Method

This sample code shows the use of the OpenReport Method (Application Object). Modify the following sample code to fit your needs.

Dim crystlApplication As CRPEAuto.Application

Dim crystlReport As CRPEAuto.Report

Function OpenReport(ReportFileName As String) As Object

     Set crystlApplication = CreateObject("Crystal.CRPE.Application")

     Set crystlReport = crystlApplication.OpenReport(ReportFileName)

End Function

Private Sub Command1_Click()

  OpenReport ("c:\crw\reports\xtreme\wwsales.rpt")

End Sub


Sample Code - OpenSubreport Method

This sample code shows the use of the OpenSubreport Method (Report Object). Modify the following sample code to fit your needs.

Dim test As Integer

    Dim crystalreport As CRPEAuto.Report

    Dim subrep1 As CRPEAuto.Report

    Dim subrep2 As CRPEAuto.Report

Function OpenSubreport(SubreportName As String) As Object

Private Sub OpenSubreport_Click()

    'valid subreport

    test = 1

    Set crystalreport = app.OpenReport(SubReport)

    Set subrep1 = crystalreport.OpenSubreport("subauton")

    subrep1.Preview

End Sub


Sample Code - Preview Method

This sample code shows the use of the Preview Method (Report Object) Modify the following sample code to fit your needs.

    Dim crystalreport As CRPEAuto.Report

    Dim repView As CRPEAuto.View

    Dim crwApplication As CRPEAuto.Application

Private Sub Command1_Click()

    'report object that view belongs to

    Set crwApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalreport = crwApplication.OpenReport _

    ("c:\crw\reports\xtreme\wwsales.rpt")

    Set repView = crystalreport.Preview

    'call procedure to check repView.Report

    Call RepCheck(crystalreport, repView.Report)

    repView.Close

End Sub


Sample Code - PrevPageButtonClicked Event

This sample code shows the use of the PrevPageButtonClicked Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub PrevPageButtonClicked_Click()

'Starts up report window for window event PrevPageButtonClicked

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.PrintWindowButtonEventEnabled & _

    Chr(13) & Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.PrintWindowButtonEventEnabled = False

        MsgBox "Check event does not occur when previous page button
clicked"

    Else

        rpt.EventInfo.PrintWindowButtonEventEnabled = True

        test = MsgBox("Check event occurs when previous page button
clicked" & _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    rptView.ShowNthPage (5)

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & crsApp.LastErrorCode &
_

        "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & rpt.LastErrorCode & _

        "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub windowEvs_PrevPageButtonClicked(useDefault As Boolean)

'executed when previous page button clicked

    If def Then

    'test for default behaviour:

        MsgBox "Window PrevPageButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Preview should _

        go to previous page"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window PrevPageButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Preview should _

        NOT go to previous page"

    End If

End Sub


Sample Code - PrintButtonClicked Event

This sample code shows the use of the PrintButtonClicked Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub PrintButtonClicked_Click()

'Starts up report window for window event PrintButtonClicked

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.PrintWindowButtonEventEnabled & _

    Chr(13) & Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.PrintWindowButtonEventEnabled = False

        MsgBox "Check event does not occur when print button clicked"

    Else

        rpt.EventInfo.PrintWindowButtonEventEnabled = True

        test = MsgBox("Check event occurs when print button clicked" & _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & crsApp.LastErrorCode &
_

        "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & rpt.LastErrorCode & _

        "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub windowEvs_PrintButtonClicked(useDefault As Boolean)

'executed when window print button clicked

    If def Then

    'test for default behaviour:

        MsgBox "Window PrintButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Print dialog should now appear"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window PrintButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Print dialog should NOT appear"

    End If

End Sub


Sample Code - PrintOut Method

This sample code shows the use of the PrintOut Method (Report Object). Modify the following sample code to fit your needs.

    Dim crystalreport As CRPEAuto.Report

    Dim repView As CRPEAuto.View

    Dim test As Integer

    Dim crwApplication As CRPEAuto.Application

Private Sub Command1_Click()

'prints view

    Set crwApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalreport = crwApplication.OpenReport _

    ("c:\crw\reports\xtreme\wwsales.rpt")

    crystalreport.PrintWindowOptions.CanDrillDown = True

    Set repView = crystalreport.Preview

    'print view

    repView.PrintOut

End Sub


Sample Code - PrintSetupButtonClicked Event

This sample code shows the use of the PrintSetupButtonClicked Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub PrintSetupButtonClicked_Click()

'Starts up report window for window event PrintSetupButtonClicked

On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    rpt.PrintWindowOptions.HasPrintSetupButton = True

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.PrintWindowButtonEventEnabled & Chr(13) & _

    Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.PrintWindowButtonEventEnabled = False

        MsgBox "Check event does not occur when print setup button
clicked"

    Else

        rpt.EventInfo.PrintWindowButtonEventEnabled = True

        test = MsgBox("Check event occurs when print setup button
clicked" & _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & crsApp.LastErrorCode &
_

        "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & rpt.LastErrorCode & _

        "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub PrintSetupButtonClicked_Click()

'Starts up report window for window event PrintSetupButtonClicked

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport(SimpleReport)

    rpt.PrintWindowOptions.HasPrintSetupButton = True

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.PrintWindowButtonEventEnabled & _

    Chr(13) & Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.PrintWindowButtonEventEnabled = False

        MsgBox "Check event does not occur when print setup button
clicked"

    Else

        rpt.EventInfo.PrintWindowButtonEventEnabled = True

        test = MsgBox("Check event occurs when print setup button
clicked" & _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.


Sample Code - ReadingRecords Event

This sample code shows the use of the ReadingRecords Event (Report Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub ReadingRecords_Click()

'Starts up report for report event ReadingRecords

Dim rptView As CRPEAuto.View

Dim test As Integer

    On Error GoTo ErrorHandler

    Set repEvs =
crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    test = MsgBox("Event default: Enabled = " & _

    repEvs.EventInfo.ReadingRecordEventEnabled & Chr(13) & _

    Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        repEvs.EventInfo.ReadingRecordEventEnabled = False

        MsgBox "Check event does not occur when report is reading
records"

    Else

        repEvs.EventInfo.ReadingRecordEventEnabled = True

        MsgBox "Check event occurs when report is reading records"

    End If

    Set rptView = repEvs.Preview

    rptView.Close

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & crsApp.LastErrorCode &
_

        "->" & crsApp.LastErrorString

    End If

    If repEvs.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & repEvs.LastErrorCode &
_

        "->" & repEvs.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    repEvs.ClearError

    Resume Next

End Sub

Private Sub repEvs_ReadingRecords(ByVal RecordsRead As Long, _

    ByVal RecordsSelected As Long, ByVal Cancelled As Boolean, _

    ByVal done As Boolean)

'executed when crpe is reading records - reading occurs at random
intervals,

'so different number of events may occur each time a report runs

    MsgBox "Report ReadingRecords event" & Chr(13) & Chr(13) & _

    "Parameters:" & Chr(13) & "RecordsRead: " & RecordsRead & _

    Chr(13) & "RecordsSelected: " & RecordsSelected & Chr(13) & _

    "Cancelled: " & Cancelled & Chr(13) & "Done: " & done

End Sub


Sample Code - RefreshButtonClicked Event

This sample code shows the use of the RefreshButtonClicked Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub RefreshButtonClicked_Click()

'Starts up report window for window event RefreshButtonClicked

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    rpt.PrintWindowOptions.HasRefreshButton = True

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.PrintWindowButtonEventEnabled & Chr(13) & _

    Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.PrintWindowButtonEventEnabled = False

        MsgBox "Check event does not occur when refresh button clicked"

    Else

        rpt.EventInfo.PrintWindowButtonEventEnabled = True

        test = MsgBox("Check event occurs when refresh button clicked" &
_

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & crsApp.LastErrorCode &
_

        "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & rpt.LastErrorCode & _

        "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub windowEvs_RefreshButtonClicked(useDefault As Boolean)

'executed when window refresh button clicked

    If def Then

    'test for default behaviour:

        MsgBox "Window RefreshButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Report should now refresh"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window RefreshButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "useDefault: " & _

        useDefault & Chr(13) & Chr(13) & "Report should NOT refresh"

    End If

End Sub


Sample Code - SearchButtonClicked Event

This sample code shows the use of the SearchButtonClicked Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub SearchButtonClicked_Click()

'Starts up report window for window event SearchButtonClicked

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    rpt.PrintWindowOptions.HasSearchButton = True

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.PrintWindowButtonEventEnabled & Chr(13) & _

    Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.PrintWindowButtonEventEnabled = False

        MsgBox "Check event does not occur when search button clicked"

    Else

        rpt.EventInfo.PrintWindowButtonEventEnabled = True

        test = MsgBox("Check event occurs when search button clicked" & _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & _

        crsApp.LastErrorCode & "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & _

        rpt.LastErrorCode & "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub windowEvs_SearchButtonClicked(ByVal SearchString As String,
_

                        useDefault As Boolean)

'executed when window search button clicked

    If def Then

    'test for default behaviour:

        MsgBox "Window SearchButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "SearchString: " & _

        SearchString & Chr(13) & "useDefault: " & useDefault & _

        Chr(13) & Chr(13) & "Search should occur"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window SearchButtonClicked event" & Chr(13) & _

        Chr(13) & "Parameters:" & Chr(13) & "SearchString: " & _

        SearchString & Chr(13) & "useDefault: " & useDefault & _

        Chr(13) & Chr(13) & "Search should NOT occur"

    End If

End Sub


Sample Code - Section Object

This sample code shows the use of the Section Object. Modify the following sample code to fit your needs.

Private Sub Command1_Click()

    On Error GoTo Command1_Click_Error

    Dim crystalApplication As CRPEAuto.Application

    Dim crystalReport As CRPEAuto.Report

    Dim crystalArea As CRPEAuto.Area

    Dim crystalSection As CRPEAuto.Section

    Dim lngSectionHeight As Long

    Dim lngSectionWidth As Long

    Set crystalApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalReport = crystalApplication.OpenReport _

    ("d:\crw\reports\craze\wwsales.rpt")

    Set crystalArea = crystalReport.Areas.Item(1)

    Set crystalSection = crystalArea.Sections(1)

    lngSectionHeight = crystalSection.Height

    lngSectionWidth = crystalSection.Width

    MsgBox "In twips the Crystal section is " & _

    Format(lngSectionHeight, "######") & " x " & _

    Format(lngSectionWidth, "######")

    Set crystalReport = Nothing

    Set crystalArea = Nothing

    Set crystalSection = Nothing

    Kill "d:\crw\reports\xtreme\wwsales.rpt"

Command1_Click_Exit:

    Exit Sub

Command1_Click_Error:

  If crystalApplication Is Nothing Then

      MsgBox "Unable to CreateObject(""Crystal.CRPE.Application"")"

      GoTo Command1_Click_Exit

  End If

  If crystalReport Is Nothing Then

      MsgBox "Unable to
OpenReport(""d:\crw\reports\craze\wwsales.rpt"")"

      GoTo Command1_Click_Exit

  End If

  MsgBox "Unknown error in Command1_Click routine"

  GoTo Command1_Click_Exit

End Sub


Sample Code - SetLogOnInfo Method

This sample code shows the use of the SetLogOnInfo Method (DatabaseTable Object). Modify the following sample code to fit your needs.

Option Explicit

Dim app1 As CRPEAuto.Application

Dim rpt1 As CRPEAuto.Report

Private Sub Form_Load()

    Set app1 = CreateObject("Crystal.CRPE.Application)

    Set rpt1 = app1.OpenReport("c:\reports\myreport.rpt")

End Sub

Private Sub Command1_Click()

    ' Set log on info for the two tables in the report

    rpt1.Database.Tables(1).SetLogOnInfo "CRSS", _

        "pubs", "user1", "password"

    rpt1.Database.Tables(2).SetLogOnInfo "CRSS", _

        "pubs", "user1", "password"

    ' Preview the report

    rpt1.Preview

End Sub


Sample Code - ShowGroup Event

This sample code shows the use of the ShowGroup Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As CRPEAuto.Integer

Private Sub ShowGroup_Click()

'Starts up report window for window event ShowGroup

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    rpt.PrintWindowOptions.HasGroupTree = True

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.GroupEventEnabled & Chr(13) & Chr(13) & _

    "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.GroupEventEnabled = False

        MsgBox "Check event does not occur when group in group tree
clicked"

    Else

        rpt.EventInfo.GroupEventEnabled = True

        test = MsgBox("Check event occurs when group in group tree
clicked" & _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & _

        crsApp.LastErrorCode & "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & _

        rpt.LastErrorCode & "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub windowEvs_ShowGroup(ByVal GroupNameList As Variant, _

                    useDefault As Boolean)

'executed when group in group tree clicked

Dim x As Integer

    For x = LBound(GroupNameList) To UBound(GroupNameList)

        MsgBox "GroupName" & x & ": " & GroupNameList(x)

    Next x

    If def Then

    'test for default behaviour:

        MsgBox "Window ShowGroup event" & Chr(13) & Chr(13) & _

        "Parameters:" & Chr(13) & "GroupNameList: " & _

        GroupNameList(UBound(GroupNameList)) & Chr(13) & _

        "useDefault: " & useDefault & Chr(13) & Chr(13) & _

        "Show group should occur"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window ShowGroup event" & Chr(13) & Chr(13) & _

        "Parameters:" & Chr(13) & "GroupNameList: " & _

        GroupNameList(UBound(GroupNameList)) & Chr(13) & _

        "useDefault: " & useDefault & Chr(13) & Chr(13) & _

        "Show group should NOT occur"

    End If

End Sub


Sample Code - SortField Object

This sample code shows the use of the SortField Object. Modify the following sample code to fit your needs.

    Dim crystalreport As CRPEAuto.Report

    Dim sortFlds As CRPEAuto.SortFields

    Dim sortFld As CRPEAuto.SortField

    Dim fldDef As CRPEAuto.Object 'field definition

    Dim crwApplication As CRPEAuto.Application

Private Sub Command1_Click()

    'returns/sets field definition for sort field

    'name for record sort field

    Set crwApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalreport = crwApplication.OpenReport _

    ("c:\crw\reports\xtreme\wwsales.rpt")

    Set sortFlds = crystalreport.RecordSortFields

    sortFlds.Add crDescending, "{Customer.Region}"

    Set sortFld = sortFlds.Item(1)

    Set fldDef = sortFld.Field

    MsgBox "Name for record sort field: " & fldDef.Name

End Sub


Sample Code - SQLQueryString Property

This sample code shows the use of the SQLQueryString Property of the Report Object. Modify the following sample code to fit your needs.

Option Explicit

Dim app1 As CRPEAuto.Application

Dim rpt1 As CRPEAuto.Report

Private Sub Form_Load()

    Set app1 = CreateObject("Crystal.CRPE.Application)

    Set rpt1 = app1.OpenReport("c:\reports\myreport.rpt")

End Sub

Private Sub Command1_Click()

    Dim sqlString As String

    ' Change log on info for the report

    rpt1.Database.Tables(1).SetLogOnInfo "CRSS", _

        "pubs", "user1", "password"

    rpt1.Database.Tables(2).SetLogOnInfo "CRSS", _

        "pubs", "user1", "password"

    ' Change the SQL query of the report

    sqlString = "SELECT publishers.pub_name, titles.title, _

        titles.ytd_sales" & Chr$(13)

    sqlString = sqlString & "FROM pubs.dbo.publishers publishers, _

        pubs.dbo.titles titles" & Chr$(13)

    sqlString = sqlString & "WHERE publishers.pub_id = _

        titles.pub_id" & Chr$(13)

    sqlString = sqlString & "AND publishers.pub_name = _

        'Binnet & Hardley'" & Chr$(13)

    sqlString = sqlString & "ORDER BY publishers.pub_name ASC"

    rpt1.SQLQueryString = sqlString

    ' Preview the report

    rpt1.Preview

End Sub


Sample Code - Start Event

This sample code shows the use of the Start Event (Report Object). Modify the following sample code to fit your needs.

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub Start_Click()

'Starts up report for report event Start

On Error GoTo ErrorHandler

    Set repEvs =
crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    test = MsgBox("Event default: Enabled = " & _

    repEvs.EventInfo.StartStopEventEnabled & Chr(13) & _

    Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        repEvs.EventInfo.StartStopEventEnabled = False

        MsgBox "Check event does not occur when report starts"

        Set rptView = repEvs.Preview

        rptView.Close

    Else

        repEvs.EventInfo.StartStopEventEnabled = True

        test = MsgBox("Check event occurs when report starts" & _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

            Set rptView = repEvs.Preview

            rptView.Close

        Else

            def = False

            repEvs.Preview

        End If

    End If

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & _

        crsApp.LastErrorCode & "->" & crsApp.LastErrorString

    End If

    If repEvs.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & _

        repEvs.LastErrorCode & "->" & repEvs.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & _

        "->" & Err.Description

    End If

    Call ResetErr

    repEvs.ClearError

    Resume Next

End Sub

Private Sub repEvs_Start(ByVal Destination As
CRPEAuto.CRPrintingDestination, _

                useDefault As Boolean)

'executed when report starts - test with and without default behaviour

    If def Then

    'test with default behaviour

        MsgBox "Report Start event" & Chr(13) & Chr(13) & "Parameters:" &
_

        Chr(13) & "Destination(window=1): " & Destination & _

        Chr(13) & "useDefault: " & useDefault & Chr(13) & _

        Chr(13) & "Report should now start"

    Else

    'test with no default behaviour

        useDefault = False

        MsgBox "Report Start event" & Chr(13) & Chr(13) & _

        "Parameters:" & Chr(13) & "Destination(window=1): " & _

        Destination & Chr(13) & "useDefault: " & useDefault & _

        Chr(13) & Chr(13) & "Report should NOT start"

    End If

End Sub


Sample Code - Stop Event

This sample code shows the use of the Stop Event (Report Object). Modify the following sample code to fit your needs.

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub Stop_Click()

'Starts up report for report event Stop

On Error GoTo ErrorHandler

    Set repEvs =
crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    test = MsgBox("Event default: Enabled = " & _

    repEvs.EventInfo.StartStopEventEnabled & Chr(13) & _

    Chr(13) & "Disable event?", vbYesNo)

    If test = vbYes Then

        repEvs.EventInfo.StartStopEventEnabled = False

        MsgBox "Check event does not occur when report stops"

    Else

        repEvs.EventInfo.StartStopEventEnabled = True

        MsgBox "Check event occurs when report stops"

    End If

    Set rptView = repEvs.Preview

    rptView.Close

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & _

        crsApp.LastErrorCode & "->" & crsApp.LastErrorString

    End If

    If repEvs.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & _

        repEvs.LastErrorCode & "->" & repEvs.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    repEvs.ClearError

    Resume Next

End Sub

Private Sub repEvs_Stop(ByVal Destination As
CRPEAuto.CRPrintingDestination, _

                ByVal Status As CRPEAuto.CRPrintingProgress)

    MsgBox "Report Stop event" & Chr(13) & Chr(13) & _

    "Parameters:" & Chr(13) & "Destination(window=1): " & _

    Destination & Chr(13) & "Status(complete=3): " & Status

End Sub


Sample Code - SubReportObject Object

This sample code shows the use of the SubreportObject Object. Modify the following sample code to fit your needs.

Class SubreportObject

    Dim crystalreport As CRPEAuto.Report

    Dim sectsVar As CRPEAuto.Sections

    Dim sectVar As CRPEAuto.Section

    Dim objs As CRPEAuto.ReportObjects

    Dim subObj As CRPEAuto.SubreportObject

    Dim test As Integer

    Dim crwApplication As CRPEAuto.Application

Private Sub Command1_Click()

    'returns the subreport name

    test = 1

    Set crwApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalreport = crwApplication.OpenReport _

    ("c:\crw\reports\xtreme\wwsales.rpt")

    Set sectsVar = crystalreport.Sections

    Set sectVar = sectsVar.Item("RF")

    Set objs = sectVar.ReportObjects

    sortFlds.Add crDescending, "{Customer.Region}"

    Set subObj = objs.Item(1)

    MsgBox "Name of subreport(autonum.rpt): " & subObj.Name

End Sub


Sample Code - TextObject Object

This sample code shows the use of the TextObject Object. Modify the following sample code to fit your needs.

Class TextObject

Private Sub Ps_Count_Click()

    'returns number of paragraph objects in a text object

    Dim crystalreport As CRPEAuto.Report

    Dim sectsVar As CRPEAuto.Sections

    Dim sectVar As CRPEAuto.Section

    Dim objs As CRPEAuto.ReportObjects

    Dim textObj As CRPEAuto.TextObject

    Dim parsObj As CRPEAuto.Paragraphs

    Dim test As Integer

    On Error GoTo ErrorHandler

    test = 1

    Set crystalreport = app.OpenReport(ManyObjsReport)

    Set sectsVar = crystalreport.Sections

    Set sectVar = sectsVar.Item("RF")

    Set objs = sectVar.ReportObjects

    Set textObj = objs.Item(3)


Sample Code - View Object

This sample code shows the use of the View Object. Modify the following sample code to fit your needs.

    Dim repWindow As CRPEAuto.Window

    Dim repViews As CRPEAuto.Views

    Dim repView As CRPEAuto.View

Private Sub Command1_Click()

'tests View.Close

    Set repWindow = repViewObj.Parent

    Set repViews = repWindow.Views

    Set repView =     repViews.GetItem(repViews.Count)

    If repViews.Count <> 1 Then

        MsgBox "Top view should close but window should remain open"

    Else

        MsgBox "Window should close - end of Close test"

        CloseView.Visible = False

    End If

    repViewObj.Close

End Sub


Sample Code - Window Object

This sample code shows the use of the Window Object. Modify the following sample code to fit your needs.

    Dim test As Index

    Dim crwApplication As CRPEAuto.Application

    Dim crystalreport As CRPEAuto.Report

    Dim repView As CRPEAuto.View

    Dim repWindow As CRPEAuto.Window

Private Sub Command1_Click()

    'parent object that view belongs to      (window)

    Set crwApplication = CreateObject("Crystal.CRPE.Application")

    Set crystalreport = crwApplication.OpenReport _

    ("c:\crw\reports\xtreme\wwsales.rpt")

    Set repView = crystalreport.Preview

    Set repWindow = repView.Parent

    'test window to ensure it is referenced correctly

    MsgBox "Window controls visible? " & repWindow.ControlsVisible

    If MsgBox("Close window?", vbYesNo) = vbYes Then

        repWindow.Close

    End If

End Sub


Sample Code - ZoomLevelChanging Event

This sample code shows the use of the ZoomLevelChanging Event (Window Object). Modify the following sample code to fit your needs.

Dim rpt As CRPEAuto.Report

Dim rptView As CRPEAuto.View

Dim test As Integer

Private Sub ShowGroup_Click()

'Starts up report window for window event ShowGroup

    On Error GoTo ErrorHandler

    Set rpt = crsApp.OpenReport("c:\crw\reports\xtreme\www.sales.rpt")

    rpt.PrintWindowOptions.HasGroupTree = True

    test = MsgBox("Event default: Enabled = " & _

    rpt.EventInfo.GroupEventEnabled & Chr(13) & Chr(13) & _

    "Disable event?", vbYesNo)

    If test = vbYes Then

        rpt.EventInfo.GroupEventEnabled = False

        MsgBox "Check event does not occur when group in group tree
clicked"

    Else

        rpt.EventInfo.GroupEventEnabled = True

        test = MsgBox("Check event occurs when group in group tree
clicked" & _

        Chr(13) & Chr(13) & "Use default behaviour for test? ", vbYesNo)

        If test = vbYes Then

            def = True

        Else

            def = False

        End If

    End If

    Set rptView = rpt.Preview

    Set windowEvs = rptView.Parent

Exit Sub        ' Exit to avoid handler.

ErrorHandler:

    If crsApp.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & _

        crsApp.LastErrorCode & "->" & crsApp.LastErrorString

    End If

    If rpt.LastErrorCode <> 0 Then

        MsgBox "Unexpected application error: " & _

        rpt.LastErrorCode & "->" & rpt.LastErrorString

    End If

    If Err.Number <> 0 Then

        MsgBox "Unexpected VB error: " & Err.Number & "->" &
Err.Description

    End If

    Call ResetErr

    rpt.ClearError

    Resume Next

End Sub

Private Sub windowEvs_ShowGroup(ByVal GroupNameList As Variant, _

                    useDefault As Boolean)

'executed when group in group tree clicked

Dim x As Integer

    For x = LBound(GroupNameList) To UBound(GroupNameList)

        MsgBox "GroupName" & x & ": " & GroupNameList(x)

    Next x

    If def Then

    'test for default behaviour:

        MsgBox "Window ShowGroup event" & Chr(13) & Chr(13) & _

        "Parameters:" & Chr(13) & "GroupNameList: " & _

        GroupNameList(UBound(GroupNameList)) & Chr(13) & _

        "useDefault: " & useDefault & Chr(13) & Chr(13) & _

        "Show group should occur"

    Else

    'test for no default behaviour:

        useDefault = False

        MsgBox "Window ShowGroup event" & Chr(13) & Chr(13) & _

        "Parameters:" & Chr(13) & "GroupNameList: " & _

        GroupNameList(UBound(GroupNameList)) & Chr(13) & _

        "useDefault: " & useDefault & Chr(13) & Chr(13) & _

        "Show group should NOT occur"

    End If

End Sub


Code samples for the Crystal Report Engine

This section provides code samples using the Crystal Report Engine. The code samples are written in C, dBASE, Delphi, and Visual Basic and can be easily incorprated into your applicaion.

  • Crystal Report Engine Functions Sample Code in C
  • Crystal Report Engine Functions Sample Code in dBASE
  • Crystal Report Engine Functions Sample Code in Delphi
  • Crystal Report Engine Functions Sample Code in Visual Basic


Crystal Report Engine Functions Sample Code in C

The following examples cover most of the major functions of the Crystal Report Engine as well as some practical examples.

Click the appropriate link to jump to that section:

  • C code for PECheckGroupSelectionFormula
  • C code for PECheckSelectionFormula
  • C code for PECloseWindow
  • C Code for PEConvertPFInfoToVInfo
  • C code for PEConvertVInfoToPFInfo
  • C code for PEDeleteNthSortField and PEDeleteNthGroupSortField
  • C code for PEDiscardSavedData and PEHasSavedData
  • C code for PEExportTo
  • C code for PEGetExportOptions
  • C code for PEGetGraphData and PESetGraphData
  • C code for PEGetGraphOptions and PESetGraphOptions
  • C code for PEGetGraphText and PESetGraphText
  • C code for PEGetGraphType and PESetGraphType
  • C code for PEGetJobStatus
  • C code for PEGetMargins and PESetMargins
  • C code for PEGetMinimumSectionHeight and PESetMinimumSectionHeight
  • C code for PEGetNDetailCopies and PESetNDetailCopies
  • C code for PEGetNFormulas, PEGetNthFormula, and PECheckFormula
  • C code for PEGetNGroups, PEGetGroupCondition, and PESetGroupCondition
  • C code for PEGetNTables
  • C code for PEGetNthTableLocation
  • C code for PEGetNthTableLogOnInfo and PESetNthTableLogOnInfo
  • C code for PEGetNthTableSessionInfo and PESetNthTableSessionInfo
  • C code for PEGetNthTableType
  • C code for PEGetNParams, PEGetNthParam, and PESetNthParam
  • C code for PEGetPrintDate and PESetPrintDate
  • C code for PEGetPrintOptions and PESetPrintOptions
  • C code for PEGetReportTitle and PESetReportTitle
  • C code for PEGetSectionFormat and PESetSectionFormat
  • C code for PEGetSelectedPrinter
  • C code for PEGetSQLQuery and PESetSQLQuery
  • C code for PEGetVersion
  • C code for PEGetWindowHandle
  • C code for PEIsPrintJobFinished
  • C code for PELogOnServer and PELogOffServer
  • C code for PENextPrintWindowMagnification and PEZoomPreviewWindow
  • C code for PEOpenEngine and PECloseEngine
  • C code for PEOpenPrintJob and PEClosePrintJob
  • C code for PEOutputToPrinter
  • C code for PEOutputToWindow
  • C code for PEPrintWindow
  • C code for PESelectPrinter
  • C code for PESetFont
  • C code for PESetNthTableLocation
  • C code for PEShowFirstPage, PEShowLastPage, PEShowNextPage, and PEShowPreviousPage
  • C code for PEShowPrintControls and PEPrintControlsShowing
  • C code for PEStartPrintJob and PECancelPrintJob
  • C code for PETestNthTableConnectivity
  • C code for getting and setting formulas
  • C code for getting and setting group selection formulas
  • C code for getting and setting group sort fields
  • C code for getting and setting selection formulas
  • C code for getting and setting sort fields
  • C code for getting error codes and error strings


C code for PECheckGroupSelectionFormula

The following code is an example of how to check if the formula text of a group selection formula is valid using PECheckGroupSelectionFormula:

if (!PECheckGroupSelectionFormula(Job)){

    // Group selection formula is invalid

}


C code for PECheckSelectionFormula

The following code is an example of how to check if the formula text of a record selection formula is valid using PECheckSelectionFormula:

if (!PECheckSelectionFormula(Job)){

    // Selection formula is invalid

}


C code for PECloseWindow

Use the following code to close the Preview Window using PECloseWindow:

PECloseWindow (Job);


C Code for PEConvertPFInfoToVInfo

The following code demonstrates how to use the PEConvertPFInfoToVInfo function:

PEParameterFieldInfo info;

PEValueInfo valueInfo;

char *tempValue;

info.StructSize = PE_SIZEOF_PARAMETER_FIELD_INFO;

valueInfo.StructSize = PE_SIZEOF_VALUE_INFO;

if (!PEGetNthParameterField(m_Job, 0, &info))

        getError();

else

{

if (!PEConvertPFInfoToVInfo(info.DefaultValue,info.    ValueType,
&valueInfo))

    getError();

else

//    if parameter 0 was type...    Then value is now in...

    Number                info.viNumber

    Currency            info.viCurrency

    Boolean                info.viBoolean

    String                info.viString

    Date                info.viDate[0] = year

                    info.viData[1] = month

                    info.viDate[2] = day

}


C code for PEConvertVInfoToPFInfo

The following code demonstrates how to use the PEConvertVInfotoPFInfofunction:

PEParameterFieldInfo info;

PEValueInfo valueInfo;
info.StructSize = PE_SIZEOF_PARAMETER_FIELD_INFO;

valueInfo.StructSize = PE_SIZEOF_VALUE_INFO;

if (PEGetNthParameterField(m_Job, 0, &info))

{

    valueInfo.valueType = info.ValueType;

    switch (info.ValueType) {

        case PE_PF_NUMBER:

            valueInfo.viNumber = 42.69;

            break;

        case PE_PF_CURRENCY:

            valueInfo.viCurrency = 995532.26;

            break;

        case PE_PF_BOOLEAN:

            valueInfo.viBoolean = 1;

            break;

        case PE_PF_STRING:

            strcpy(valueInfo.viString, "Later Yesterday");

            break;

        case PE_PF_DATE:

            valueInfo.viDate[0] := 1997;

            valueInfo.viDate[1] := 5;

            valueInfo.viDate[2] := 1;

            break;

}

    //Switch

    if (!PEConvertVInfoToPFInfo(&valueInfo, &info.ValueType,

        info.CurrentValue))

        getError();

    else

    {

        info.CurrentValueSet = TRUE;

        if (!PESetNthParameterField(m_Job, 0, &info))

            getError();

    }

}


C code for PEDeleteNthSortField and PEDeleteNthGroupSortField

Just as sort fields and group sort fields can be added or changed with PESetNthSortField and PESetNthGroupSortField, they can also be deleted using PEDeleteNthSortField and PEDeleteNthGroupSortField. The following code is an example of how to use these functions:

PEDeleteNthSortField

short            sortFieldN;

    // the sort field to be deleted
sortFieldN = 1;

    // Delete the second sort field
if (!PEDeleteNthSortField(Job, sortFieldN)){

    // Handle error

}

PEDeleteNthGroupSortField

short            groupSortFieldN;

    // the group sort field to be deleted
groupSortFieldN = 0;

    // Delete the first group sort field
if (!PEDeleteNthGroupSortField(Job, groupSortFieldN)){

    // Handle error

}


C code for PEDiscardSavedData and PEHasSavedData

The following code demonstrates how to check with the PEHasSavedData function to see if a report contains saved data and, if so, how to discard the saved data using the PEDiscardSavedData function:

BOOL        hasSavedData;

if (!PEHasSavedData(Job, &hasSavedData)){

    // Handle error

}

if (hasSavedData){

    // does the report have saved data?

    if (!PEDiscardSavedData(Job)){

        // Handle error

    }

}


C code for PEExportTo

The following code demonstrates the use of the PEExportOptions structure and the PEExportTo function to specify an export destination and format for a report. Use PEExportTo as an alternative to PEOutputToWindow and PEOutputToPrinter. In this example, the specified report is exported to a disk file in Character Separated Values format:

// Note: UXFSEPV.H and UXDDISK.H must be #included

// for this example to work. Refer to the

// PEExportTo function and the

// PEExportOptions structure for more information.
struct UXFCharSeparatedOptions charSepOptions;

// For formatOptions
struct UXDDiskOptions diskOptions;

// For destinationOptions
struct PEExportOptions exportOptions;
// Initialize members of charSepOptions

charSepOptions.structSize = UXFCharSeparatedOptionsSize;
// Use number format saved in report

charSepOptions.useReportNumberFormat = TRUE;
// Do not use date format saved in report

charSepOptions.useReportDateFormat = FALSE;
// No quotes around values

charSepOptions.stringDelimeter = '^';
// Character separator is *

charSepOptions.fieldDelimeter = "*";
// Initialize members of diskOptions

diskOptions.structSize = UXDDiskOptionsSize;

diskOptions.fileName = "c:\reports\myreport.rpt";
// Initialize members of exportOptions

exportOptions.StructSize = PE_SIZEOF_EXPORT_OPTIONS;

lstrcpy(exportOptions.formatDLLName, "uxfsepv.dll");

exportOptions.formatType = UXFCharSeparatedType;

exportOptions.formatOptions = &charSepOptions;

lstrcpy(exportOptions.destinationDLLName, "uxddisk.dll");

exportOptions.destinationType = UXDDiskType;

exportOptions.destinationOptions = &diskOptions;
if (!PEExportTo(Job, &exportOptions))
{

    // Handle error
}


C code for PEGetExportOptions

To have the Report Engine prompt a user for information to use in the PEExportOptions structure before calling PEExportTo, you can use the PEGetExportOptions function. The following code demonstrates how to call this function:

struct PEExportOptions exportOptions;

exportOptions.StructSize = PE_SIZEOF_EXPORT_OPTIONS;

if (!PEGetExportOptions(Job, &exportOptions)){

    // Handle error

}

    // Now PEExportOptions is filled in

    // We can call PEExportTo
if (!PEExportTo(Job, &exportOptions)){

    // Handle error

}


C code for PEGetGraphData and PESetGraphData

Use the following code as an example of how to call the PEGetGraphData and PESetGraphData functions:

PEGetGraphData

short            sectionCode,

    // The report section the graph is in

    graphN;

    // The graph number in the section

struct PEGraphDataInfo graphDataInfo;

sectionCode = PE_DETAILSECTION;

    // Graph is in Details section

graphN = 0;

    // First graph in section

    // Initialize size of graphDataInfo structure

graphDataInfo.StructSize = sizeof(PEGraphDataInfo);

if (!PEGetGraphData(Job, sectionCode, graphN, &graphDataInfo)){

    // Handle error

}

PESetGraphData

short            sectionCode,

    // The report section the graph is in

    graphN;

    // The graph number in the section

struct PEGraphDataInfo graphDataInfo;

sectionCode = PE_HEADERSECTION;

    // Graph is in Page Header section

graphN = 1;

    // Second graph in section

    // Initialize members of graphDataInfo structure

graphDataInfo.StructSize = sizeof(PEGraphDataInfo);

graphDataInfo.rowGroupN = 1;

    // Use value in Group 1 for rows

graphDataInfo.colGroupN = 2;

    // Use value in Group 2 for columns

graphDataInfo.summarizedFieldN = 0;

    // First summarized field

graphDataInfo.graphDirection = PE_MIXED_ROW_COL;

if (!PESetGraphData(Job, sectionCode, graphN, &graphDataInfo)){

    // Handle error

}


C code for PEGetGraphOptions and PESetGraphOptions

Use the following code as an example of how to call the PEGetGraphOptions and PESetGraphOptions functions:

PEGetGraphOptions

short         sectionCode,

    // The report section the graph is in

    graphN;

    // The graph number in the section

struct PEGraphOptions graphOptions;

sectionCode = PE_DETAILSECTION;

    // Graph is in Details section

graphN = 0;

    // First graph in section

    // Initialize size of graphOptions structure

graphOptions.StructSize = sizeof(PEGraphOptions);

if (! PEGetGraphOptions(Job, sectionCode, graphN, &graphOptions)){

    // Handle error

}

PESetGraphOptions

short            sectionCode,

    // The report section the graph is in

    graphN;

    // The graph number in the section

struct PEGraphOptions graphOptions;

sectionCode = PE_HEADERSECTION;

    // Graph is in Page Header section

graphN = 1;

    // Second graph in section

    // Initialize members of graphOptions structure

graphOptions.StructSize = sizeof(PEGraphDataInfo);

graphOptions.graphMaxValue = 100;    // Do not graph values over 100

graphOptions.graphMinValue = 10;     // Do not graph values under 10

graphOptions.showDataValue = TRUE;    // Show data values on risers

graphOptions.showGridLine = TRUE;    // Show grid lines

graphOptions.verticalBars = FALSE;    // Use Horizontal bars in bar graph

graphOptions.showLegend = FALSE;    // Do not use a legend

lstrcpy(graphOptions.fontFaceName, "Courier");  // Use Courier font

if (! PESetGraphOptions(Job, sectionCode, graphN, &graphOptions)){

    // Handle error

}


C code for PEGetGraphText and PESetGraphText

Use the following code as an example of how to call the PEGetGraphText and PESetGraphText functions:

PEGetGraphText

short             sectionCode,

    // The report section the graph is in

    graphN;

    // The graph number in the section

struct PEGraphTextInfo graphTextInfo;

sectionCode = PE_DETAILSECTION;

    // Graph is in Details section

graphN = 0;

    // First graph in section

    // Initialize size of graphTextInfo structure

graphTextInfo.StructSize = sizeof(PEGraphTextInfo);

if (! PEGetGraphText(Job, sectionCode, graphN, &graphTextInfo)){

    // Handle error

}

PESetGraphText

short            sectionCode,

    // The report section the graph is in

    graphN;

    // The graph number in the section

struct PEGraphTextInfo graphTextInfo;

sectionCode = PE_HEADERSECTION;

    // Graph is in Page Header section

graphN = 1;

    // Second graph in section

    // Initialize members of graphTextInfo structure

graphTextInfo.StructSize = sizeof(PEGraphTextInfo);

lstrcpy(graphTextInfo.graphTitle, "My Graph");

lstrcpy(graphTextInfo.graphSubTitle, "Product Sales");

lstrcpy(graphTextInfo.graphFootNote, "A Footnote");

lstrcpy(graphTextInfo.graphGroupsTitle, "Groups");

lstrcpy(graphTextInfo.graphSeriesTitle, ""); // No Series Title

lstrcpy(graphTextInfo.graphXAxisTitle, "X Axis");

lstrcpy(graphTextInfo.graphYAxisTitle, "Y Axis");

lstrcpy(graphTextInfo.graphZAxisTitle, ""); // For 3D graphs only

if (! PESetGraphText(Job, sectionCode, graphN, &graphTextInfo)){

    // Handle error

}


C code for PEGetGraphType and PESetGraphType

Use the following code as an example of how to call the PEGetGraphType and PESetGraphType functions:

PEGetGraphType

short            sectionCode,

    // The report section the graph is in

    graphN,

    // The graph number in the section

    graphType;

    // The type of graph

sectionCode = PE_GROUPHEADER;

    // Graph is in Group Header section

graphN = 0;            // First graph in section

if (!PEGetGraphType(Job, sectionCode, graphN, &graphType)){

    // Handle error

}
    // graphType now contains a PE graph type value

PESetGraphType

short                sectionCode,

    // The report section the graph is in

    graphN,

    // The graph number in the section

    graphType;

    // The type of graph

sectionCode = PE_GROUPHEADER;                            // Graph is in Group Header section

graphN = 0;                        // First graph in section

graphType = PE_THREED_BAR_GRAPH;                        // Use 3D Bar graph

if (!PESetGraphType(Job, sectionCode, graphN, &graphType)){

    // Handle error

}


C code for PEGetJobStatus

The following code is an example of how to use the PEGetJobStatus function to get the status of a print job, along with other information regarding the current job:

short            status;

struct     PEJobInfo jobInfo;

    // Initialize size of structure

jobInfo.StructSize = sizeof(PEJobInfo);

status = PEGetJobStatus(Job, &jobInfo);


C code for PEGetMargins and PESetMargins

The following code demonstrates how to use the PEGetMargins and PESetMargins functions:

PEGetMargins

short        left,

        right,

        top,

        bottom;

if (!PEGetMargins(Job, &left, &right, &top, &bottom)){

    // Handle error

}

PESetMargins

short        left,

        right,

        top,

        bottom;

left = 1440;            // in twips

right = 1440;            // in twips

top = PE_SM_DEFAULT;        // Default top margin

bottom = PE_SM_DEFAULT;    // Default bottom margin

if (!PESetMargins(Job, left, right, top, bottom)){

    // Handle error

}


C code for PEGetMinimumSectionHeight and PESetMinimumSectionHeight

The following code demonstrates how to call the PEGetMinimumSectionHeight and PESetMinimumSectionHeight functions:

PEGetMinimumSectionHeight

short        sectionCode;                // The section we are interested in

short    minimumHeight;            // The minimum height for the section

sectionCode = PE_GRANDTOTALSECTION;    // Grand Total section

if (!PEGetMinimumSectionHeight(Job, sectionCode, &minimumHeight)){

    // Handle error

}

PESetMinimumSectionHeight

short        sectionCode;                // The section to be changed

short    minimumHeight;            // The new minimum height

sectionCode = PE_GROUPHEADER;        // Group Header section

minimumHeight = 2880;            // in twips

if (!PESetMinimumSectionHeight(Job, sectionCode, minimumHeight)){

    // Handle error

}


C code for PEGetNDetailCopies and PESetNDetailCopies

The following code demonstrates how to use the PEGetNDetailCopies and PESetNDetailCopies functions:

PEGetNDetailCopies

short            nDetailCopies;

    // # of copies of detail section to print

if (!PEGetNDetailCopies(Job, &nDetailCopies)){

    // Handle error

}

PESetNDetailCopies

short        nDetailCopies;

    // # of copies of detail section to print

nDetailCopies = 2;

    // print 2 copies of each detail section

if (!PESetNDetailCopies(Job, nDetailCopies)){

    // Handle error

}


C code for PEGetNFormulas, PEGetNthFormula, and PECheckFormula

The following code provides examples of how the functions PEGetNFormulas, PEGetNthFormula, and PECheckFormula can be used:

PEGetNFormulas

short        nFormulas;

nFormulas = PEGetNFormulas(Job);

if (nFormulas < 0){

    // Handle error

}

PEGetNthFormula

short            formulaN;

    // the formula we are interested in

HANDLE    nameHandle;

short        nameLength;

char        *nameString;

HANDLE    textHandle;

short        textLength;

char        *textString;
formulaN = 0;

    // Get information on the first formula in the report

if (!PEGetNthFormula(Job, formulaN, &nameHandle, &nameLength,

&textHandle, &textLength)){

    // Handle error

}

    // Allocate buffers

nameString = (char*)malloc(nameLength);

textString = (char*)malloc(textLength);

if (!PEGetHandleString(nameHandle, nameString, nameLength)){

    // Handle error

}

if (!PEGetHandleString(textHandle, textString, textLength)){

    // Handle error

}

PECheckFormula

char formulaName [] = "MyFormula";
    // Check to see if the formula text in @MyFormula is valid

if (!PECheckFormula(Job, formulaName)){

    // Formula is invalid

}


C code for PEGetNGroups, PEGetGroupCondition, and PESetGroupCondition

Following are examples of how to use the PEGetNGroups, PEGetGroupCondition, and PESetGroupCondition functions:

PEGetNGroups

short            nGroups;

    // Number of groups in report

nGroups = PEGetNGroups(Job);

if (nGroups < 0){

    // Handle error

}

PEGetGroupCondition

BOOL            result;

short        sectionCode;

    // Group header or group footer

HANDLE    conditionFieldHandle;

short        conditionFieldLength;

char        *conditionFieldString;

short        condition;

    // Will receive a PE_GC_ value

Note: For a list of PE_GC_ values, see PESetGroupCondition.

    short        sortDirection;

    // Will receive Ascending or Descending

sectionCode = PE_GROUPFOOTER;

    // Group footer section

result = PEGetGroupCondition(Job, sectionCode, &conditionFieldHandle,
&conditionFieldLength, &condition, &sortDirection);

if (!result){

    // Handle error

}

    // Allocate buffer

conditionFieldString = (char*)malloc(conditionFieldLength);

result = PEGetHandleString(conditionFieldHandle, conditionFieldString,
conditionFieldLength);

if (!result){

    // Handle error

}

PESetGroupCondition

BOOL            result;

short        sectionCode;

short        condition;

short        sortDirection;

char         conditionField [] = "{orders.DATE}";

sectionCode = PE_GROUPFOOTER;

condition = PE_GC_MONTHLY;

    // New group for every month

sortDirection = PE_SF_ASCENDING;

result = PESetGroupCondition(Job, sectionCode, conditionField, condition,
sortDirection);

if (!result){

    // Handle error

}


C code for PEGetNTables

Use the following code as an example of how to use the PEGetNTables function to find out how many tables are used in a report:

short        nTables;

    // Will hold the number of tables

nTables = PEGetNTables(Job);

if (nTable <= 0){

    // Handle error

}


C code for PEGetNthTableLocation

Use the following code as an example of how to call PEGetNthTableLocation:

short         tableN;

struct PETableLocation tableLocation;

tableN = 0;

    // Get location of first table in report

    // Initialize size of structure

tableLocation.StructSize = PE_SIZEOF_TABLE_LOCATION;

if (!PEGetNthTableLocation(Job, tableN, &tableLocation){

    // Handle error

}


C code for PEGetNthTableLogOnInfo and PESetNthTableLogOnInfo

The following code is an example of how to use the PEGetNthTableLogOnInfo and PESetNthTableLogOnInfo functions:

PEGetNthTableLogOnInfo

short            tableN;

struct PELogOnInfo logOnInfo;

tableN = 1;

    // Get information on the second table in the report

    // Initialize size of structure

logOnInfo.StructSize = PE_SIZEOF_LOGON_INFO;

if (!PEGetNthTableLogOnInfo(Job, tableN, &logOnInfo)){

    // Handle error

}

PESetNthTableLogOnInfo

short            tableN;

BOOL        propagate;

struct PELogOnInfo logOnInfo;

tableN = 0;

propagate = False;

    // Log on only valid for the first table.

    // Initialize structure

logOnInfo.StructSize = PE_SIZEOF_LOGON_INFO;

lstrcpy(logOnInfo.ServerName, "Server");

lstrcpy(logOnInfo.DatabaseName, "database");

lstrcpy(logOnInfo.UserID, "user ID");

lstrcpy(logOnInfo.Password, "password");

if (!PESetNthTableLogOnInfo(Job, tableN, &logOnInfo, propagate)){

    // Handle error

}


C code for PEGetNthTableSessionInfo and PESetNthTableSessionInfo

If your application uses Microsoft Access database tables, you may need to examine or change session information when an Access session is to be opened. The following code is an example of how to use the PEGetNthTableSessionInfo and PESetNthTableSessionInfo functions when using Access databases.

PEGetNthTableSessionInfo

short            tableN;

    // The table number in the report

struct PESessionInfo sessionInfo;

tableN = 1;

    // The second table in the report

    // Initialize size of sessionInfo structure

sessionInfo.StructSize = PE_SIZEOF_SESSION_INFO;

if (!PEGetNthTableSessionInfo(Job, tableN, &sessionInfo)){

    // Handle error

}

PESetNthTableSessionInfo

short            tableN;

    // The table number in the report

struct PESessionInfo sessionInfo;

BOOL     propagateAcrossTables;

    // Use for all tables in report?

tableN = 0;    // The first table in the report

propagateAcrossTables = TRUE;

    // Initialize size of sessionInfo structure

sessionInfo.StructSize = PE_SIZEOF_SESSION_INFO;

sessionInfo.UserID = "user";

sessionInfo.Password = "password";

sessionInfo.SessionHandle = 0;

if (!PESetNthTableSessionInfo(Job, tableN, &sessionInfo,

propagateAcrossTables)){

    // Handle error

}


C code for PEGetNthTableType

Use the following code as an example of how to use the PEGetNthTableType function to find out the type of table being used in a particular report:

short        tableN;

struct PETableType tableType;

tableN = 0;

    // Obtain information about the first table in the report.

    // Initialize size of structure

tableType.StructSize = PE_SIZEOF_TABLE_TYPE;

if (!PEGetNthTableType(Job, tableN, &tableType)){

    // Handle error

}


C code for PEGetNParams, PEGetNthParam, and PESetNthParam

If the report being accessed by the Report Engine uses a SQL database table that is based on a stored procedure, you may wish to examine and change the parameters of that procedure. The following code demonstrates how to use the PEGetNParams, PEGetNthParam, and PESetNthParam functions to work with stored procedures:

PEGetNParams

short            nParams;

    // Number of parameters in stored procedure

nParams = PEGetNParams(Job);

if (nParams < 0){

    // Handle error

}

PEGetNthParam

short            paramN;

    // The parameter we are interested in

HANDLE    textHandle;

short        textLength;

char        *textString;

paramN = 0;

    // First parameter in stored procedure

if (!PEGetNthParam(Job, paramN, &textHandle, &textLength)){

    // Handle error

}

    // Allocate buffer

textString = (char*)malloc(textLength);

    // Retrieve string

if (!PEGetHandleString(textHandle, textString, textLength)){

    // Handle error

}

    // textString now contains the value of

    // the first parameter in the stored procedure.

PESetNthParam

short            paramN;

    // The parameter to be changed

char szParamValue [] = "1005";

    // Pass numeric value to parameter

paramN = 1;

    // Change second parameter in stored procedure

if (!PESetNthParam(Job, paramN, szParamValue)){

    // Handle error

}


C code for PEGetPrintDate and PESetPrintDate

The following code shows how the print date, as set in the report, can be retrieved using PEGetPrintDate and changed using PESetPrintDate:

PEGetPrintDate

short            year,

        month,

        day;

if (!PEGetPrintDate(Job, &year, &month, &day)){

    // Handle error

}

PESetPrintDate

short            year,

        month,

        day;

year = 1999;

month = 05;

day = 30;

if (!PESetPrintDate(Job, year, month, day)){

    // Handle error

}


C code for PEGetPrintOptions and PESetPrintOptions

Print options can be examined and changed using PEGetPrintOptions and PESetPrintOptions. The following code demonstrates how to use these functions:

PEGetPrintOptions

struct PEPrintOptions printOptions;

    // Initialize size of structure

printOptions.StructSize = sizeof(PEPrintOptions);

if (!PEGetPrintOptions(Job, &printOptions)){

    // Handle error

}

PESetPrintOptions

struct PEPrintOptions printOptions;

    // Initialize structure

printOptions.StructSize = sizeof(PEPrintOptions);

printOptions.startPageN = 1;

    // Start printing at page 1

printOptions.stopPageN = 10;

    // Stop printing after page 10

printOptions.nReportCopies = 2;

    // Print 2 copies of the report

printOptions.collation = PE_COLLATED;

    // Collate the copies

if (!PESetPrintOptions(Job, &printOptions)){

    // Handle error

}


C code for PEGetReportTitle and PESetReportTitle

Use the following code as an example of how to call the PEGetReportTitle and PESetReportTitle functions:

PEGetReportTitle

HANDLE        titleHandle;

short        titleLength;

char        *titleString;

if (!PEGetReportTitle(Job, &titleHandle, &titleLength)){

    // Handle error

}

    // Allocate buffer

titleString = (char*)malloc(titleLength);

if (!PEGetHandleString(titleHandle, titleString, titleLength)){

    // Handle error

}

PESetReportTitle

char title [] = "My Report";

if (!PESetReportTitle(Job, title)){

    // Handle error

}


C code for PEGetSectionFormat and PESetSectionFormat

The following code demonstrates how to use the PEGetSectionFormat and PESetSectionFormat functions:

PEGetSectionFormat

short        sectionCode;

    // The section we are interested in

struct PESectionOptions options;

sectionCode = PE_DETAILSECTION;

    // The details section

    // Initialize size of options structure

options.StructSize = sizeof(PESectionOptions);

if (!PEGetSectionFormat(Job, sectionCode, &options)){

    // Handle error

}

PESetSectionFormat

short        sectionCode;

    // The section we are interested in

struct PESectionOptions options;

sectionCode = PE_DETAILSECTION;

    // The details section

    // Initialize options structure

options.StructSize = sizeof(PESectionOptions);

options.visible = TRUE;

options.newPageBefore = FALSE;

options.newPageAfter = FALSE;

options.keepTogether = TRUE;

options.suppressBlankLines = PE_UNCHANGED;

    // leave as is

options.resetPageNAfter = FALSE;

options.printAtBottomOfPage = FALSE;

if (!PESetSectionFormat(Job, sectionCode, &options)){

    // Handle error

}


C code for PEGetSelectedPrinter

The following code demonstrates how to use the PEGetSelectedPrinter function:

BOOL            result;

HANDLE    driverHandle;

short        driverLength;

char        *driverString;

HANDLE    printerHandle;

short        printerLength;

char        *printerString;

HANDLE    portHandle;

short        portLength;

char        *portString;

struct     DEVMODE *pd;

result = PEGetSelectedPrinter(Job, &driverHandle,

&driverLength, &printerHandle, &printerLength,

&portHandle, &portLength, &pd);

if (!result){

    // Handle error

}

    // Allocate buffers

driverString = (char*)malloc(driverLength);

printerString = (char*)malloc(printerLength);

portString = (char*)malloc(portLength);

    // Retrieve strings
if (!PEGetHandleString(driverHandle, driverString, driverLength)){

    // Handle error

}

if (!PEGetHandleString(printerHandle, printerString, interLength)){

    // Handle error

}

if (!PEGetHandleString(portHandle, portString, portLength)){

    // Handle error

}


C code for PEGetSQLQuery and PESetSQLQuery

Use the following code as an example of how to get the text in a SQL query with PEGetSQLQuery, and how to change a SQL query with PESetSQLQuery:

PEGetSQLQuery

HANDLE        textHandle;

short        textLength;

char        *textString;

if (!PEGetSQLQuery(Job, &textHandle, &textLength)){

    // Handle error

}

// Allocate buffer

textString = (char*)malloc(textLength);

if (!PEGetHandleString(textHandle, textString, textLength)){

    // Handle error

}

    // textString now contains the SQL query

PESetSQLQuery

char queryString [] = "SELECT orders.ORDERNUM, orders.AMOUNT

            FROM sales.orders orders

            WHERE orders.AMOUNT > 1000.00";

if (!PESetSQLQuery(Job, queryString)){

    // Handle error

}


C code for PEGetVersion

The following code can be used to get the current version number of CRPE.DLL and the Report Engine using PEGetVersion:

short         versionRequested, currentVersion;

versionRequested = PE_GV_DLL;

currentVersion = PEGetVersion(versionRequested);

if (currentVersion < 0){

    // Handle error

}


C code for PEGetWindowHandle

Use code similar to the following to obtain the handle to the Preview Window using PEGetWindowHandle:

HWND        hWnd;

hWnd = PEGetWindowHandle(Job);

if (hWnd <= 0){

    // Handle error

}


C code for PEIsPrintJobFinished

Use the following code to check to see if a print job is finished using PEIsPrintJobFinished:

if (PEIsPrintJobFinished(Job)){

    // print job is finished

} else {

    // print job has not finished

}


C code for PELogOnServer and PELogOffServer

PELogOnServer allows you to log on to a SQL Server without specifying a particular report file. Use the following code as an example of how to log on to a Server with PELogOnServer, then log off with PELogOffServer:

PELogOnServer

struct PELogOnInfo logOnInfo;

    // Initialize structure

logOnInfo.StructSize = PE_SIZEOF_LOGON_INFO;

lstrcpy(logOnInfo.ServerName,"Server");

lstrcpy(logOnInfo.DatabaseName,"database");

lstrcpy(logOnInfo.UserID,"user ID");

lstrcpy(logOnInfo.Password, "password");

    // Connect to the server

if(!PELogOnServer("PDSODBC.DLL", &logOnInfo)){

    // Handle error

    PEClosePrintJob(Job);

    // close the print job

    return;

}

PELogOffServer

if(!PELogOffServer("PDSODBC.DLL", &logOnInfo)){

    // Handle error

}


C code for PENextPrintWindowMagnification and PEZoomPreviewWindow

The following code demonstrates how to change Preview Window magnification using PENextPrintWindowMagnification and PEZoomPreviewWindow:

PENextPrintWindowMagnification

if (!PENextPrintWindowMagnification(Job)){

    // Handle error

}

PEZoomPreviewWindow

short            zoomLevel;

zoomLevel = PE_ZOOM_SIZE_FIT_BOTH_SIDES;

    // Fit both sides of report

if (!PEZoomPreviewWindow(Job, zoomLevel)){

    // Handle error

}


C code for PEOpenEngine and PECloseEngine

Use the following code to open the Report Engine with PEOpenEngine, then close the Report Engine with PECloseEngine:

if (!PEOpenEngine()){

    // Handle error

}

PECloseEngine();


C code for PEOpenPrintJob and PEClosePrintJob

The following code is an example of how to open a new print job with PEOpenPrintJob, then close the print job with PEClosePrintJob:

Note: PEOpenPrintJob returns the job handle. This value is implied in all other sample code appearing in this Help file.

    short     Job;

char     *reportFile;

lstrcpy(reportFile, "c:\crw\myreport.rpt");

Job = PEOpenPrintJob(reportFile);

if (Job <= 0){

    // Handle error

}

if (!PEClosePrintJob(Job)){

    // Handle error

}


C code for PEOutputToPrinter

The following code is an example of how to use the PEOutputToPrinter function:

short        nCopies;

nCopies = 2;

    // Print 2 copies of the report.
if (!PEOutputToPrinter(Job, nCopies)){

    // Handle error

}


C code for PEOutputToWindow

Use the following code as an example of how to call the PEOutputToWindow function:

short            left,

        top,

        width,

        height;

long        style;

HWND        parentWindow;
char title [] = "My Report";

left = 0;

top = 0;

width = 500;

    // screen units

height = 500;

    // screen units

style = 0;

parentWindow = 0;
if (!PEOutputToWindow(Job, title, left, top, width,

height, style, parentWindow)){

    // Handle error

}


C code for PEPrintWindow

Use the following code to print the Preview Window to a printer using PEPrintWindow:

BOOL         waitUntilDone;

waitUntilDone = True;

if (!PEPrintWindow(Job, waitUntilDone)){

    // Handle error

}


C code for PESelectPrinter

The PESelectPrinter function uses the Windows DEVMODE structure to allow you to select a specific printer for the report to be printed to. The following sample code demonstrates how to use the DEVMODE structure and PESelectPrinter:

struct DEVMODE mode;

char      driverName [] = "EPSON24";

char     printerName [] = "Epson LQ-850";

char     portName [] = "LPT1:";
    // Initialize DEVMODE values to zero

memset(&mode, 0, sizeof(mode));
    // Initialize DEVMODE structure with appropriate values

lstrcpy(mode.dmDeviceName, "Epson LQ-850");

mode.dmSpecVersion = 0x30A;

mode.dmDriverVersion = 2;

mode.dmSize = sizeof(DEVMODE);

mode.dmDriverExtra = 0;

mode.dmFields = (DM_ORIENTATION | DM_PAPERSIZE | DM_COPIES |

DM_DEFAULTSOURCE | DM_PRINTQUALITY | DM_TTOPTION);

mode.dmOrientation = DMORIENT_LANDSCAPE;

mode.dmPaperSize = DMPAPER_LETTER;

mode.dmCopies = 2;

mode.dmDefaultSource = DMBIN_AUTO;

mode.dmPrintQuality = DMRES_HIGH;

mode.dmTTOption = DMTT_BITMAP;
if (!PESelectPrinter(Job, driverName, printerName, portName, &mode)){

    // Handle error

}


C code for PESetFont

The following sample code demonstrates how to use the PESetFont function:

BOOL        result;

short    sectionCode,            // The section to change font in

    scopeCode,            // Apply to fields or text?

    fontFamily,

    fontPitch,

    charSet,

    pointSize,

    isItalic,

    isUnderlined,

    isStruckOut,

    weight;

char faceName [] = "Arial";        // Use the Arial font face

sectionCode = PE_ALLSECTIONS;        // Apply change to all sections

scopeCode = PE_FIELDS | PE_TEXT;    // Apply to both fields and text

fontFamily = FF_DONTCARE;        // Use default

fontPitch = DEFAULT_PITCH;

charSet = ANSI_CHARSET;        // Use ANSI Character set

pointSize = 12;

isItalic = PE_UNCHANGED;        // Keep as is

isUnderlined = TRUE;            // Underline characters

isStruckOut = FALSE;

weight = FW_BOLD;            // Bold text

result = PESetFont(Job, sectionCode, scopeCode, faceName, fontFamily,
fontPitch, charSet, pointSize, isItalic, isUnderlined, isStruckOut, weight);

if (!result){

    // Handle error

}


C code for PESetNthTableLocation

The following code demonstrates how to use the PESetNthTableLocation function to set a new location for a table in the report:

short            tableN;

    // The table number in the report

struct PETableLocation location;

tableN = 0;

    // The first table in the report

    // Initialize values in location structure

location.StructSize = PE_SIZEOF_TABLE_LOCATION;

location.Location = "C:\\TABLES\\mydb.mdb";

if (!PESetNthTableLocation(Job, tableN, &location)){

    // Handle error

}


C code for PEShowFirstPage, PEShowLastPage, PEShowNextPage, and PEShowPreviousPage

The procedure for calling PEShowFirstPage, PEShowLastPage, PEShowNextPage, and PEShowPreviousPage is identical for each function. The following code demonstrates how to call the PEShowNextPage function, but the same procedure can be used when calling any of the four functions:

if (!PEShowNextPage(Job)){

    // Handle error

}


C code for PEShowPrintControls and PEPrintControlsShowing

The following code demonstrates how to use the PEPrintControlsShowing function to find out if the Print Controls are showing in the Preview Window, and how to display the Print Controls in the Preview Window with the PEShowPrintControls function if they are not showing:

BOOL            controlsShowing,

        showPrintControls;

if (!PEPrintControlsShowing(Job, &controlsShowing)){

    // Handle error

}

if (!controlsShowing){    // Controls are not showing

    showPrintControls = TRUE;

    If (!PEShowPrintControls(Job, showPrintControls)){

        // Handle error

    }

}


C code for PEStartPrintJob and PECancelPrintJob

The following code provides an example of how to use PEStartPrintJob to start a print job, then how to use PECancelPrintJob to cancel it. Once a print job is started, it must finish before the next line of code in the procedure can execute. For this reason, PECancelPrintJob can only cancel the print job if executed from a different code procedure. For example, PEStartPrintJob may execute as the result of a Print button being clicked, while PECancelPrintJob can cancel the job as the result of a separate Cancel button being clicked. If PECancelPrintJob appears in the same event procedure as PEStartPrintJob, it will have no effect.

PEStartPrintJob

BOOL         waitUntilDone;

waitUntilDone = True;

    // waitUntilDone must always be True

if (!PEStartPrintJob(Job, waitUntilDone)){

    // Handle error

}

PECancelPrintJob

PECancelPrintJob(Job);


C code for PETestNthTableConnectivity

Use the following code as an example of how to find out if a SQL table can be accessed before trying to log on to it. This demonstrates the PETestNthTableConnectivity function:

short            tableN;

    // The SQL table you want to test

tableN = 0;

    // Test the first table in the report

if (!PETestNthTableConnectivity(Job, tableN)){

    // Handle error

}


C code for getting and setting formulas

The following code demonstrates the use of PEGetFormula to retrieve the text of a named formula and PESetFormula to change the text of a named formula:

PEGetFormula

HANDLE        textHandle;

short        textLength;

char        *formulaString;
char formulaName [] = "MyFormula";
if (!PEGetFormula(Job, formulaName, &textHandle, &textLength)){

    // Handle error

}
    // Allocate formulaString buffer

formulaString = (char*)malloc(textLength);
    // Retrieve actual formula string

if (!PEGetHandleString(textHandle, formulaString, textLength)){

    // Handle error

}
    // formulaString now contains text of named formula

PESetFormula

char formulaName [] = "MyFormula";

char formulaString [] = "{salesrep.SALES} * .10";

    // 10% commission
if (!PESetFormula(Job, formulaName, formulaString)){

    // Handle error

}


C code for getting and setting group selection formulas

The following code demonstrates the use of the PEGetGroupSelectionFormula and PESetGroupSelectionFormula functions:

PEGetGroupSelectionFormula

HANDLE        textHandle;

short        textLength;

char        *formulaString;

if (!PEGetGroupSelectionFormula(Job, &textHandle, &textLength)){

    // Handle error

}

    // Allocate formulaString buffer

formulaString = (char*)malloc(textLength);

    // Retrieve actual formula string

if (!PEGetHandleString(textHandle, formulaString, textLength)){

    // Handle error

}

    // formulaString now contains text of group selection formula

PESetGroupSelectionFormula

char groupSelectionFormula [] = "Sum({orders.AMOUNT},

{orders.CUSTOMER}) > 10000.00";

if (!PESetSelectionFormula(Job, groupSelectionFormula)){

    // Handle error

}


C code for getting and setting group sort fields

The Crystal Report Engine includes two functions for getting information from a report about group sort fields:

  • PEGetNGroupSortFields, and
  • PEGetNthGroupSortField,

as well as a third function for changing information in an existing group sort field or adding a new group sort field to the report, PESetNthGroupSortField. The following sample code demonstrates techniques for using each of these three functions:

short         nGroupSortFields;                // Will receive number of sort fields

short     groupSortFieldN;        // Indicates specific group sort field

HANDLE nameHandle;            // Pointer to name of group sort field

short     nameLength;            // Length of group sort field name

short     direction;            // Sort direction

char   *groupSortFieldName         // Holds actual group sort field name

short     newDirection            // New group sort field direction

char   newGroupSortName [] = "Count({customer.CUSTOMER},

{customer.CITY})";            // New group sort field name
nGroupSortFields = PEGetNGroupSortFields(Job);

if (nGroupSortFields < 0){

    // Handle error

}
groupSortFieldN = 0;

// The first group sort field in the report
if (!PEGetNthGroupSortField(Job, groupSortFieldN, &nameHandle,

&nameLength, &direction)){

    // Handle error

}
    // nameLength now contains the length of the string in nameHandle

    // direction now contains either

    // PE_SF_ASCENDING or PE_SF_DESCENDING
    // allocate groupSortFieldName buffer

groupSortFieldName = (char*)malloc(nameLength);
    // Retrieve the group sort field name

if (!PEGetHandleString(nameHandle, groupSortFieldName,nameLength)){

    // Handle error

}
    // groupSortFieldName now contains the group sort field

    // Now we will add a new group sort field

newDirection = PE_SF_ASCENDING
    // By using the value returned by PEGetNGroupSortFields in
    // PESetNthGroupSortField, we add a new group

    // sort field to the report:
if (!PESetNthGroupSortField(Job, nGroupSortFields,

newGroupSortName, newDirection)){

    // Handle error

}


C code for getting and setting selection formulas

The following code demonstrates the use of the PEGetSelectionFormula and PESetSelectionFormula functions:

PEGetSelectionFormula

HANDLE        textHandle;

short        textLength;

char        *formulaString;

if (!PEGetSelectionFormula(Job, &textHandle, &textLength)){

    // Handle error

}

    // Allocate formulaString buffer

formulaString = (char*)malloc(textLength);

    // Retrieve actual formula string

if (!PEGetHandleString(textHandle, formulaString, textLength)){

    // Handle error

}

    // formulaString now contains text of selection formula

PESetSelectionFormula

char selectionFormula [] = "{orders.AMOUNT} > 1000.00";

if (!PESetSelectionFormula(Job, selectionFormula)){

    // Handle error

}


C code for getting and setting sort fields

The Crystal Report Engine includes two functions for getting information from a report about sort fields, PEGetNSortFields and PEGetNthSortField, as well as a third function for changing information in an existing sort field or adding a new sort field to the report, PESetNthSortField. The following sample code demonstrates techniques for using each of these three functions:

short            nSortFields;

    // Will receive number of sort fields

short        sortFieldN;

    // Indicates specific sort field

HANDLE nameHandle;

    // Pointer to name of sort field

short         nameLength;

    // Length of sort field name

short         direction;

    // Sort direction

char     *sortFieldName

    // Holds actual sort field name

short         newDirection

    // New sort field direction

char      newSortName [] = "{orders.ORDERNUM}";

    // New sort field name

nSortFields = PEGetNSortFields(Job);

if (nSortFields < 0){

    // Handle error

}

sortFieldN = 0;

    // Get information for the first sort

    // field in the report

if (!PEGetNthSortField(Job, sortFieldN, &nameHandle,

&nameLength, &direction)){

    // Handle error

}

    // nameLength now contains the length of the string in nameHandle

    // direction now contains either

    // PE_SF_ASCENDING or PE_SF_DESCENDING

    // allocate sortFieldName buffer

sortFieldName = (char*)malloc(nameLength);

    // Retrieve the sort field name

if (!PEGetHandleString(nameHandle, sortFieldName, nameLength)){

    // Handle error

}

    // sortFieldName now contains the sort field

    // Now we will add a new sort field

newDirection = PE_SF_ASCENDING
    // By using the value returned by PEGetNSortFields in

    // PESetNthSortField, we add a new sort field to the report:

if (!PESetNthSortField(Job, nSortFields, newSortName,

newDirection))

{

    // Handle error

}


C code for getting error codes and error strings

Retrieving Report Engine error codes and errors is an important task in creating successful Report Engine applications. Use the following code for PEGetErrorCode and PEGetErrorText as an example of how to handle errors:

short            errorCode;

HANDLE    errorHandle;

short        errorLength;

char        *errorString;

errorCode = PEGetErrorCode(Job);

if (errorCode < 0){

    // Handle error

} else {

    if (errorCode = 0){ // No error }

}

if (!PEGetErrorText(Job, &errorHandle, &errorLength)){

    // Handle error

}

    // Allocate string buffer

errorString = (char*)malloc(errorLength);

    // Retrieve error string

if (!PEGetHandleString(errorHandle, errorString, errorLength)){

    // Handle error

}


Crystal Report Engine Functions Sample Code in dBASE

The following examples cover most of the major functions of the Crystal Report Engine as well as some practical examples.

Click the appropriate link to jump to that section:

  • dBASE code for PECheckGroupSelectionFormula
  • dBASE code for PECheckSelectionFormula
  • dBASE code for PECloseWindow
  • dBASE code for PEDeleteNthSortField and PEDeleteNthGroupSortField
  • dBASE code for PEDiscardSavedData
  • dBASE code for PEGetNFormulas and PECheckFormula
  • dBASE code for PEGetNGroups and PESetGroupCondition
  • dBASE code for PEGetNTables
  • dBASE code for PEGetVersion
  • dBASE code for PEGetWindowHandle
  • dBASE code for PEIsPrintJobFinished
  • dBASE code for PENextPrintWindowMagnification and PEZoomPreviewWindow
  • dBASE code for PEOpenEngine and PECloseEngine
  • dBASE code for PEOpenPrintJob and PEClosePrintJob
  • dBASE code for PEOutputToPrinter
  • dBASE code for PEOutputToWindow
  • dBASE code for PEPrintWindow
  • dBASE code for PESetFont
  • dBASE code for PESetMargins
  • dBASE code for PESetMinimumSectionHeight
  • dBASE code for PESetNDetailCopies
  • dBASE code for PESetPrintDate
  • dBASE code for PESetReportTitle
  • dBASE code for PEShowFirstPage, PEShowLastPage, PEShowNextPage, and PEShowPreviousPage
  • dBASE code for PEShowPrintControls
  • dBASE code for PEStartPrintJob and PECancelPrintJob
  • dBASE code for PETestNthTableConnectivity
  • dBASE code for getting error codes
  • dBASE code for setting formulas
  • dBASE code for setting group selection formulas
  • dBASE code for setting group sort fields
  • dBASE code for setting selection formulas
  • dBASE code for setting sort fields


dBASE code for PECheckGroupSelectionFormula

The following code is an example of how to use the PECheckGroupSelectionFormula function to check a group selection formula for errors:

IF PECheckGroupSelectionFormula(Job) = .F.

    && Handle error

ENDIF


dBASE code for PECheckSelectionFormula

The following code is an example of how to use the PECheckSelectionFormula function to check a record selection formula for errors:

IF PECheckSelectionFormula(Job) = .F.

    && Handle error

ENDIF


dBASE code for PECloseWindow

Use the following code to close the Preview Window using PECloseWindow:

PECloseWindow (Job)


dBASE code for PEDeleteNthSortField and PEDeleteNthGroupSortField

You can use code similar to this to delete a sort field using PEDeleteNthSortField and a group sort field using PEDeleteNthGroupSortField:

PEDeleteNthSortField

LOCAL FieldToDelete

FieldToDelete = 0

    && Let's delete the first sort field

IF PEDeleteNthSortField (Job, FieldToDelete) = .F.

    && Handle error

ENDIF

PEDeleteNthGroupSortField

LOCAL FieldToDelete

FieldToDelete = 0

    && Let's delete the first group sort field

IF PEDeleteNthGroupSortField (Job, FieldToDelete) = .F.

    && Handle error

ENDIF


dBASE code for PEDiscardSavedData

The following code is an example of how to use the PEDiscardSavedData function:

IF PEDiscardSavedData(Job) = .F.

    && Handle error

ENDIF


dBASE code for PEGetNFormulas and PECheckFormula

The following code is an example of how to use the PEGetNFormulas function:

LOCAL nNumFormulas

nNumFormulas = PEGetNFormulas(Job)

IF nNumFormulas < 0

    && Function failed

ENDIF

The following code is an example of how to use the PECheckFormula to check a named formula for errors:

LOCAL result, cFormulaName

cFormulaName = "MyFormula"

result = PECheckFormula(Job, cFormulaName)

IF result = .F.

    && Handle Error

ENDIF


dBASE code for PEGetNGroups and PESetGroupCondition

Use the following code as an example of how to use the PEGetNGroups to get the number of groups in a report:

LOCAL nNumGroups

nNumGroups = PEGetNGroups(Job)

IF nNumGroups < 0

    && Handle error

ENDIF

You can use code similar to the following to change the condition for a group field in your report using PESetGroupCondition:

LOCAL SectionCode, ConditionField, Condition, SortDirection

SectionCode = PE_GROUPFOOTER

    && Indicates the Group Footer Section

ConditionField = "{ALIAS.TABLE->BOOLFIELD}"

Condition = PE_GC_TOYES

SortDirection = PE_SF_ASCENDING

IF PESetGroupCondition (Job, SectionCode, ConditionField,;

    Condition, SortDirection) = .F.

    && Handle error

ENDIF


dBASE code for PEGetNTables

Use code similar to the following to query the number of tables in a report using PEGetNTables:

LOCAL NumTables

NumTables = PEGetNTables (Job)

IF NumTables < 0

    && Handle error

ENDIF


dBASE code for PEGetVersion

You can use code similar to this whenever you want to get the version number of the DLL or the Crystal Report Engine using PEGetVersion:

LOCAL version

version = PEGetVersion (PE_GV_DLL)


dBASE code for PEGetWindowHandle

Use code similar to the following to obtain the handle to the Preview Window using PEGetWindowHandle:

LOCAL Handle

Handle = PEGetWindowHandle (Job)

IF Handle = 0

    && Error

ENDIF


dBASE code for PEIsPrintJobFinished

Use the following code to check to see if a print job is finished using PEIsPrintJobFinished:

result = PEIsPrintJobFinished(Job)

IF result

    MSGBOX("The Print Job has finished.", "Message", 0)

ELSE

    MSGBOX("The Print Job is not finished.", "Message", 16)

ENDIF


dBASE code for PENextPrintWindowMagnification and PEZoomPreviewWindow

The following code is an example of how to use the PENextPrintWindowMagnification function to change the Preview Window to the next level of magnification:

IF PENextPrintWindowMagnification(Job) = .F.

    && Handle error

ENDIF

Use the following code to set a specific Zoom magnification level in the Preview Window using PEZoomPreviewWindow:

LOCAL nZoomLevel

nZoomLevel = 0

    && Zoom to full page level

IF PEZoomPreviewWindow(Job, nZoomLevel) = .F.

    && Handle error

ENDIF


dBASE code for PEOpenEngine and PECloseEngine

Use the following code to open the Report Engine with PEOpenEngine, then close the Report Engine with PECloseEngine:

PEOpenEngine

Procedure Form_OnOpen

    PEOpenEngine()

    return

PECloseEngine

Procedure Form_OnClose

    PECloseEngine()

    return


dBASE code for PEOpenPrintJob and PEClosePrintJob

The following code is an example of how to open a new print job with PEOpenPrintJob, then close the print job with PEClosePrintJob.

LOCAL Job, cReport, nError

cReport = "C:\dbasewin\samples\myreport.rpt"

Job = PEOpenPrintJob(cReport)

IF Job = 0

    nError = PEGetErrorCode(Job)

    && Handle error

    PEClosePrintJob(Job)

    return

ENDIF

PEClosePrintJob(Job)


dBASE code for PEOutputToPrinter

The following code is an example of how to use the PEOutputToPrinter function:

LOCAL result, nCopies, nError

nCopies = 2

    && Print 2 copies of report

result = PEOutputToPrinter(Job, Copies)

IF result = .F.

    nError = PEGetErrorCode(Job)

    && Handle error

    PEClosePrintJob(Job)

    return

ENDIF


dBASE code for PEOutputToWindow

The following code is an example of how to use the PEOutputToWindow function:

LOCAL result, cTitle, nError

cReport = "My Report"

result = PEOutputToWindow(Job, cTitle, CW_USEDEFAULT,;

    CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0)

IF result = .F.

    nError = PEGetErrorCode(Job)

    && Handle error

    PEClosePrintJob(Job)

    return

ENDIF


dBASE code for PEPrintWindow

Use the following code to print the Preview Window to a printer using PEPrintWindow:

LOCAL Job, wait

wait = .T.

IF PEPrintWindow (Job, wait) = .F.

    && Handle error

ENDIF


dBASE code for PESetFont

You can use code similar to the following to set the font for a section of your report using PESetFont:

LOCAL SectionCode, ScopeCode, FaceName, FontFamily

LOCAL FontPitch, CharSet, PointSize, IsItalic

LOCAL IsUnderline, IsStrikeOut, Weight

SectionCode = PE_ALLSECTIONS        && Apply to all sections

ScopeCode = PE_FIELDS            && Apply to fields

FaceName = "Courier"

FontFamily = 0                && FF_DONTCARE

FontPitch = 0                && DEFAULT_PITCH

CharSet = 1                && DEFAULT_CHARSET

PointSize = 12

IsItalic = 0

IsUnderline = 0

IsStrikeOut = 0

Weight = 0

IF PESetFont (Job, SectionCode, ScopeCode, FaceName, FontFamily,;

    FontPitch, CharSet, PointSize, IsItalic, IsUnderline,;

    IsStrikeOut, Weight) = .F.

    && Handle error

ENDIF


dBASE code for PESetMargins

You can use code similar to the following whenever you want to set the margins on your report using PESetMargins:

LOCAL LMargin, RMargin, TMargin, Bmargin

IF PESetMargins (Job, LMargin, RMargin, TMargin, BMargin) = .F.

    && Handle error

ENDIF


dBASE code for PESetMinimumSectionHeight

You can use code similar to the following whenever you want to use the PESetMinimumSectionHeight to set the minimum height for a section in a report:

LOCAL Area, Height

Area = PE_HEADERSECTION

    &&Set the area of the header section

Height = 1440

    && Set the height in twips

IF PESetMinimumSectionheight (Job, Area, Height) = .F.

    && Handle error

ENDIF


dBASE code for PESetNDetailCopies

You can use code similar to the following to set the number of copies of the Details section you want the program to print using PESetNDetailCopies:

LOCAL Copies

Copies = 5

    && Print 5 copies of Details section

IF PESetNDetailCopies (Job, Copies) = .F.

    &&Handle error

ENDIF


dBASE code for PESetPrintDate

Use the following code as an example of how to change the print date using PESetPrintDate:

LOCAL nYear, nMonth, nDay

nYear = 1995

nMonth = 06

nDay = 30

IF PESetPrintDate (Job, nYear, nMonth, nDay) = .F.

    && Handle error

ENDIF


dBASE code for PESetReportTitle

This topic demonstrates the use of PESetReportTitle. Use code similar to the following whenever you want to change the current report title:

LOCAL cTitle

cTitle = "My Report"

IF PESetReportTitle (Job, cTitle) = .F.

    && Handle error

ENDIF


dBASE code for PEShowFirstPage, PEShowLastPage, PEShowNextPage, and PEShowPreviousPage

The following samples of code demonstrate how to use the PEShow functions to control which page is shown in the Preview Window:

PEShowNextPage

IF PEShowNextPage (Job) = .F.

    && Handle error

ENDIF

PEShowFirstPage

IF PEShowFirstPage (Job) = .F.

    && Handle error

ENDIF

PEShowPreviousPage

IF PEShowPreviousPage (Job) = .F.

    && Handle error

ENDIF

PEShowLastPage

IF PEShowLastPage (Job) = .F.

    && Handle error

ENDIF


dBASE code for PEShowPrintControls

The following code is an example of how to use the PEShowPrintControls function to either show the control buttons in the Preview Window or hide the control buttons:

IF PEShowPrintControls (Job, .T.) = .F.

    && Handle error

ENDIF


dBASE code for PEStartPrintJob and PECancelPrintJob

The following code provides an example of how to use the PEStartPrintJob function to start a print job, and how to use PECancelPrintJob to cancel it:

        && PEOpenPrintJob has been called,

    && and the print job number has been

    && assigned to the variable Job

LOCAL result, nError

result = PEStartPrintJob(Job, .T.)

IF result = .F.

    nError = PEGetErrorCode(Job)

    IF nError = PE_ERR_NOERROR

        PECloseWindow(Job)

    ELSE

        &&Handle error

    ENDIF

ENDIF

    && Now to cancel the print job:

PECancelPrintJob(Job)


dBASE code for PETestNthTableConnectivity

You can use code similar to the following to test the connection to the database or use PETestNthTableConnectivity to make certain it is ready for a log on whenever you print a report:

LOCAL TableNumber

TableNumber = 0

    && Examine the first table

IF PETestNthTableConnectivity(Job, TableNumber) = .F.

    && Handle Error

ENDIF


dBASE code for getting error codes

The following code is an example of how to get Report Engine error codes using PEGetErrorCode:

LOCAL nError

nError = PEGetErrorCode(Job)

IF nError = 0

    && No error

ELSEIF nError < 0

    && Function failed

ELSE

    && Report error code

ENDIF


dBASE code for setting formulas

This topic demonstrates the use of PESetFormula. You can use code similar to this at any time to change a formula string:

LOCAL nError, cFormula, cFormulaName

cFormula = "Sum({orders.LINEITEM})"

cFormulaName = "lineitemtotal"

result = PESetFormula(Job, cFormulaName, cFormula)

IF result = .F.

    nError = PEGetErrorCode(Job)

    && Handle error

    return

ENDIF


dBASE code for setting group selection formulas

This topic demonstrates the use of PESetGroupSelectionFormula. You can use code similar to the following at any time to change a group selection formula string:

LOCAL Formula

Formula = "Sum ({orders.AMT_PAID}, {orders.CUSTOMER}) > 1000.00"

IF PESetGroupSelectionFormula (Job, Formula) = .F.

    && Handle error

ENDIF


dBASE code for setting group sort fields

The following code demonstrates the use of PEGetNGroupSortFields and PESetNthGroupSortField:

LOCAL nError, nGrpSortFields

LOCAL cGrpSortField, nDirection, result

nGrpSortFields = PEGetNGroupSortFields(Job)

IF nGrpSortFields < 0

    nError = PEGetErrorCode(Job)

    && Handle error

    return

ENDIF

cGrpSortField = "Count ({customer.CUSTOMER->CITY},;

    {customer.CUSTOMER->CITY})"

nDirection = PE_SF_DESCENDING

result = PESetNthGroupSortField (Job, nGrpSortFields,;

    cGrpSortField, nDirection)

IF result = .F.

    nError = PEGetErrorCode(Job)

    && Handle error

    return

ENDIF


dBASE code for setting selection formulas

This topic demonstrates the use of PESetSelectionFormula. You can use code similar to the following at any time to change a selection formula string:

LOCAL cSelectionFormula, result

cSelectionFormula = "{salesrep.SALES} > 20000.00"

result = PESetSelectionFormula(Job, cSelectionFormula)

IF result = .F.

    nError = PEGetErrorCode(Job)

    && Handle error

    return

ENDIF


dBASE code for setting sort fields

The following code demonstrates the use of PEGetNSortFields and PESetNthSortField.

You can use code similar to the following at any time to change the sort field/sort direction:

LOCAL nError, nSortFields, cSortField, nDirection, result

nSortFields = PEGetNSortFields(Job)

IF nSortFields < 0

    nError = PEGetErrorCode(Job)

    && Handle error

    return

ENDIF

cSortField = "{alias.TABLE->FIELD}"

nDirection = PE_SF_ASCENDING

result = PESetNthSortField(Job, nSortFields, cSortField, nDirection)

IF result = .F.

    nError = PEGetErrorCode(Job)

    && Handle error

    PEClosePrintJob(Job)

    return

ENDIF


Crystal Report Engine Functions Sample Code in Delphi

The following examples cover most of the major functions of the Crystal Report Engine as well as some practical examples.

Click the appropriate link to jump to that section:

  • Delphi code for opening and closing the Print Engine
  • Delphi code for opening and closing a PrintJob
  • Delphi code for error handling
  • Delphi code for getting subreport information
  • Delphi code for getting/setting parameter field information
  • Delphi code for logging on/off a server
  • Delphi code for getting/setting table location
  • Delphi code for getting/setting formulas
  • Delphi code for getting/setting print options
  • Delphi code for getting/setting section format
  • Delphi code for getting/setting logon information
  • Delphi code for getting/setting the SQL query
  • Delphi code for exporting a report


Delphi code for opening and closing the Print Engine

Calls used
PEOpenEngine
PECanCloseEngine
PECloseEngine
Code
uses CRDelphi;

procedure OpenEngine;
begin
  {If an error occured during opening...}
  if not PEOpenEngine then
    {Do Error Handler};
end;

procedure CloseEngine;
begin
  {Check to see if Engine can be closed}
  if PECanCloseEngine then
    PECloseEngine;
end;


Delphi code for opening and closing a PrintJob

Calls used
PEOpenEngine
PEOpenPrintJob
PEOpenSubreport
PEClosePrintJob
Code
uses CRDelphi;

procedure OpenPrintJob;
var
  sTmp     : string;
  PrintJob : smallint;
begin
  {Make sure the Engine is Open}
  if not PEOpenEngine then
    {Do Error Handler};

  {Open the Main PrintJob}
  PrintJob := PEOpenPrintJob('C:\Company.rpt');
  {If PrintJob is zero, generate error}
  if PrintJob = 0 then
    {Do Error Handler};
end;

procedure OpenSubreportPrintJob;
var
  sTmp        : string;
  SubPrintJob : smallint;
begin
  {Make sure the Engine is Open}
  if not PEOpenEngine then
    {Do Error Handler};

  {Open the Main PrintJob}
  PrintJob := PEOpenPrintJob('C:\Company.rpt');
  {If PrintJob is zero, generate error}
  if PrintJob = 0 then
    {Do Error Handler};

  {Open a Subreport PrintJob}
  sTmp := 'SubreportName' + #0;
  SubPrintJob := PEOpenSubreport(PrintJob, @sTmp[1]);
  {If PrintJob is zero, generate error}
  if PrintJob = 0 then
    {Do Error Handler};
end;

procedure ClosePrintJob;
begin
  if (PrintJob <> 0) then
  begin
    {Close the Main report}
    if not PEClosePrintJob(PrintJob) then
      {Do Error Handler};
  end;
end;


Delphi code for error handling

The GetError function is a Print Engine error message capture function. It accepts the Job Number as a parameter and then gets the Error Code and Error String. It then passes this back out as a formatted string.

Calls used
PEGetErrorCode
PEGetErrorText
PEGetHandleString
Code
uses CRDelphi;
function GetError(const JobIn: smallint): string;
var
  Code      : smallint;
  StrHandle : hWnd;
  Buffer    : PChar;
  Length    : smallint;
  Ret       : Bool;
begin
  {Get the Error code from the Crpe}
  Code := PEGetErrorCode(JobIn);
  {Get the error message handle}
  Ret := PEGetErrorText(JobIn, StrHandle, Length);
  Buffer := StrAlloc(Length);
  {Get the text from the text handle}
  Ret := PEGetHandleString(StrHandle, Buffer, Length);
  {Output the string}
  if Ret then
    Result := IntToStr(Code) + ' - ' + StrPas(Buffer)
  else
    Result := 'Unknown Error';
  StrDispose(Buffer);
end;


Delphi code for getting subreport information

The code below assumes that the Main Report PrintJob is already open.

Calls used
PEGetNSections
PEGetSectionCode
PEGetNSubreportsInSection
PEGetNthSubreportInSection
PEGetSubreportInfo
Code
uses CRDelphi;

procedure GetSubreportInfo;
var
  SubreportHandle : LongInt;
  SubreportInfo   : PESubreportInfo;
  nSections,
  nSubReports     : smallint;
  nSection,
  nSubreport      : smallint;
  SectionCode     : smallint;
  SubReportName   : string;
  NLinks          : smallint;
  OnDemand        : smallint;
begin
  {Set the structure size}
  SubreportInfo.Structsize := SizeOf(PESubreportInfo);

  {Get the # of Sections in the Report}
  nSections := PEGetNSections(PrintJob);
  if nSections = -1 then
    {Do Error Handler};

  {Loop through the Sections}
  for nSection := 0 to (nSections - 1) do
  begin
    SectionCode := PEGetSectionCode(PrintJob, nSection);
    nSubReports := PEGetNSubreportsInSection(PrintJob, SectionCode);
    if nSubReports > 0 then
    begin
      for nSubreport := 0 to nSubReports - 1 do
      begin
        {Get the Subreport Handle}
        SubreportHandle := PEGetNthSubreportInSection(PrintJob,
SectionCode, nSubreport);
        {Get the Subreport Name}
        if not PEGetSubreportInfo(PrintJob, SubreportHandle,
SubreportInfo) then
          {Do Error Handler};

        {Get SubreportName and other information}
        {Normally these would be stored to stringlists, or something
similar}
        SubReportName := (StrPas(@SubreportInfo.SubreportName));
        NLinks := SubreportInfo.NLinks;
        OnDemand := SubreportInfo.isOnDemand;
      end;
    end;
  end;
end;


Delphi code for getting/setting parameter field information

The code below assumes that a PrintJob is already open.

Calls used
  {General}
PEGetNParameterFields
PEGetNthParameterField
  PESetNthParameterField
  {ParameterField To/From ValueInfo}
PEConvertPFInfoToVInfo
  PEConvertVInfoToPFInfo
  {Min/Max}
PEGetParameterMinMaxValue
  PESetParameterMinMaxValue
  {ParameterType}
PEGetNthParameterType
  {ParameterValueInfo}
PEGetParameterValueInfo
  PESetParameterValueInfo
  {DefaultValues}
PEGetNParameterDefaultValues
PEGetNthParameterDefaultValue
  PESetNthParameterDefaultValue
  PEAddParameterDefaultValue
  PEDeleteNthParameterDefaultValue
  {CurrentValues}
PEGetNParameterCurrentValues
PEGetNthParameterCurrentValue
  PEAddParameterCurrentValue
  {Ranges}
  PEClearParameterCurrentValuesAndRanges
PEGetNParameterCurrentRanges
PEGetNthParameterCurrentRange
  PEAddParameterCurrentRange
  {PromptDialog}
  PEGetAllowPromptDialog
  PESetAllowPromptDialog
Code
uses CRDelphi;

procedure GetParameterFieldInformation;
var
  ParameterInfo      : PEParameterFieldInfo;
  ParameterValueInfo : PEParameterValueInfo;
  ValueInfo,
  minValueInfo,
  maxValueInfo,
  startValueInfo,
  endValueInfo       : PEValueInfo;
  nParam,
  nParams,
  nType,
  iRangeInfo,
  nValues,
  nValue             : smallint;
  sTmp,
  sValueMin,
  sValueMax,
  sRangeStart,
  sRangeEnd          : string;
begin
  ParameterInfo.structSize      := SizeOf(PEParameterFieldInfo);
  ValueInfo.structSize          := SizeOf(PEValueInfo);
  ParameterValueInfo.structSize := SizeOf(PEParameterValueInfo);
  minValueInfo.structSize       := SizeOf(PEValueInfo);
  maxValueInfo.structSize       := SizeOf(PEValueInfo);
  startValueInfo.structSize     := SizeOf(PEValueInfo);
  endValueInfo.structSize       := SizeOf(PEValueInfo);

  {Get the Parameter Names from the Report}
  nParams :=
TPEGetNParameterFields(PEGetNParameterFields)(Cr.FPrintJob);
  if nParams = -1 then
    {Do Error Handler};

  for nParam := 0 to (nParams - 1) do
  begin
    if not PEGetNthParameterField(PrintJob, nParam, ParameterInfo) then
      {Do Error Handler};

    {These are the ParameterInfo members...}
    StrPas(@ParameterInfo.Name);
    StrPas(@ParameterInfo.ReportName);
    StrPas(@ParameterInfo.Prompt);
    ParameterInfo.CurrentValueSet;
    ParameterInfo.needsCurrentValue;
    ParameterInfo.valueType;
    ParameterInfo.isLimited;
    StrPas(ParameterInfo.EditMask);

    {Get DefaultValue into ValueInfo structure}
    ValueInfo.ValueType := ParameterInfo.valueType;
if not PEConvertPFInfoToVInfo(@ParameterInfo.DefaultValue,
ValueInfo.ValueType, ValueInfo) then
      {Do Error Handler};

    {The ValueInfo structure now holds the DefaultValue}
    {ValueInfoToStr is a sample procedure that converts the DefaultValue
     to a string; you will want to handle this differently}
sTmp := ValueInfoToStr(ValueInfo);

    {Get CurrentValue into ValueInfo structure}
    ValueInfo.ValueType := ParameterInfo.valueType;
if not PEConvertPFInfoToVInfo(@ParameterInfo.CurrentValue,
ValueInfo.ValueType, ValueInfo) then
      {Do Error Handler};

    {The ValueInfo structure now holds the CurrentValue}
    {ValueInfoToStr is a sample procedure that converts the CurrentValue
     to a string; you will want to handle this differently}
sTmp := ValueInfoToStr(ValueInfo);

    {Min and Max Size}
    if ParameterInfo.isLimited = 1 then
    begin
if not PEGetParameterMinMaxValue(PrintJob, @ParameterInfo.Name,
@ParameterInfo.ReportName, minValueInfo, maxValueInfo) then
  {Do Error Handler};

    case ParameterInfo.valueType of
        PE_PF_NUMBER,
        PE_PF_CURRENCY :
          begin
            {The min/max ValueInfo structures now hold the Min/Max values}
            {ValueInfoToStr is a sample procedure that converts the
ValueInfo
             value to a string; you will want to handle this differently}
            sValueMin := ValueInfoToStr(minValueInfo);
            sValueMax := ValueInfoToStr(maxValueInfo);
          end;
        PE_PF_STRING   :
          begin
            {The min/max ValueInfo structures now hold the Min/Max values}
            {ValueInfoToStr is a sample procedure that converts the
ValueInfo
             value to a string; you will want to handle this differently}
            sValueMin := TruncStr(ValueInfoToStr(minValueInfo));
            sValueMax := TruncStr(ValueInfoToStr(maxValueInfo));
          end;
        PE_PF_DATE,
        PE_PF_DATETIME,
        PE_PF_TIME     :
          begin
            {The min/max ValueInfo structures now hold the Min/Max values}
            {ValueInfoToStr is a sample procedure that converts the
ValueInfo
             value to a string; you will want to handle this differently}
            sValueMin := ValueInfoToStr(minValueInfo);
            sValueMax := ValueInfoToStr(maxValueInfo);
          end;
      end;
    end;

    {Parameter Type}
    nType := PEGetNthParameterType(PrintJob, nParam);
    if nType = -1 then
  {Do Error Handler};

    case nType of
      PE_PO_REPORT     : {SCR Parameter Field};
      PE_PO_STOREDPROC : {Stored Procedure Parameter};
      PE_PO_QUERY      : {Query Parameter};
    end;

    {Get PEParameterValueInfo}
if not PEGetParameterValueInfo(PrintJob, @ParameterInfo.Name,
@ParameterInfo.ReportName, ParameterValueInfo) then
  {Do Error Handler};

    {These are the ParameterValueInfo members...}
    ParameterValueInfo.isNullable;
    ParameterValueInfo.disallowEditing;
    ParameterValueInfo.allowMultipleValues;
    ParameterValueInfo.hasDiscreteValues;
    ParameterValueInfo.partOfGroup;
    ParameterValueInfo.mutuallyExclusiveGroup;
    ParameterValueInfo.groupNum;

    {Get Parameter Field DefaultValues}
    nValues := PEGetNParameterDefaultValues(PrintJob,
@ParameterInfo.Name, @ParameterInfo.ReportName);
    if nValues = -1 then
      {Do Error Handler};

    for nValue := 0 to (nValues - 1) do
    begin
      if not PEGetNthParameterDefaultValue(PrintJob,
@ParameterInfo.Name, @ParameterInfo.ReportName, nValue, ValueInfo) then
        {Do Error Handler};

      {The ValueInfo structure now holds the DefaultValue}
      {ValueInfoToStr is a sample procedure that converts the
DefaultValue
       to a string; you will want to handle this differently}
      sTmp := ValueInfoToStr(ValueInfo);
    end;

    {Get Parameter Field CurrentValues/Ranges}
    if ParameterValueInfo.hasDiscreteValues = 1 then
    begin
      nValues := PEGetNParameterCurrentValues(PrintJob,
@ParameterInfo.Name, @ParameterInfo.ReportName);
      if nValues = -1 then
        {Do Error Handler};

      for nValue := 0 to (nValues - 1) do
      begin
        if not PEGetNthParameterCurrentValue(PrintJob,
@ParameterInfo.Name, @ParameterInfo.ReportName, nValue, ValueInfo) then
          {Do Error Handler};

        {The ValueInfo structure now holds the CurrentValue}
        {ValueInfoToStr is a sample procedure that converts the
CurrentValue
         to a string; you will want to handle this differently}
        sTmp := ValueInfoToStr(ValueInfo);
      end
      else
      begin
        {Get Parameter Field Ranges}
        nValues := PEGetNParameterCurrentRanges(PrintJob,
@ParameterInfo.Name, @ParameterInfo.ReportName);
        if nValues = -1 then
          {Do Error Handler};

        {Loop through Ranges}
        for nValue := 0 to (nValues - 1) do
        begin
          iRangeInfo := 0;
          if not PEGetNthParameterCurrentRange(PrintJob,
@ParameterInfo.Name, @ParameterInfo.ReportName, nValue, startValueInfo,
endValueInfo, iRangeInfo) then
            {Do Error Handler};

          {The startValueInfo structure now holds the Range Start Value}
          {ValueInfoToStr is a sample procedure that converts the
startValueInfo
           value to a string; you will want to handle this differently}
          sRangeStart := ValueInfoToStr(startValueInfo);
          {The ValueInfo structure now holds the Range End Value}
          {ValueInfoToStr is a sample procedure that converts the
endValueInfo
           value to a string; you will want to handle this differently}
          sRangeEnd := ValueInfoToStr(endValueInfo);

          {Get Range Bounds info}
          if (iRangeInfo - PE_RI_NOLOWERBOUND > -1) then
          begin
            iRangeInfo := iRangeInfo - PE_RI_NOLOWERBOUND;
            if iRangeInfo - PE_RI_NOUPPERBOUND > -1 then
              {Upper and Lower Bounds not included in range}
            else
              {Upper Bound only included in range};
          end
          else
          begin
            if iRangeInfo - PE_RI_INCLUDELOWERBOUND > -1 then
            begin
              iRangeInfo := iRangeInfo - PE_RI_INCLUDELOWERBOUND;
              if iRangeInfo - PE_RI_INCLUDEUPPERBOUND > -1 then
                {Upper and Lower Bounds included in range}
              else
                {Lower Bound only included in range};
            end;
          end;
        end;
      end;
    end;
  end;
end;

{Returns the ValueInfo value as a formatted string}
function ValueInfoToStr (var ValueInfo: PEValueInfo): string;
var
  sTmp : string;
begin
  sTmp := '';
  case ValueInfo.ValueType of
    {Number}
    PE_PF_NUMBER : Str(ValueInfo.viNumber:0:2, sTmp);
    {Currency}
    PE_PF_CURRENCY : Str(ValueInfo.viCurrency:0:2, sTmp);
    {Boolean}
    PE_PF_BOOLEAN : sTmp := BooleanToStr(ValueInfo.viBoolean, False);
    {Date}
    PE_PF_DATE :  {YYYY,MM,DD}
      begin
        {Crystal's null datetime is -4713,1,1 0:0:0; Delphi does not
         allow for negative dates in it's TDateTime, so I use 1,1,1
instead}
        if ValueInfo.viDate[0] < 1 then
          sTmp := '1,1,1'
        else
        begin
          sTmp := IntToStr(ValueInfo.viDate[0]) + ',' +
                  IntToStr(ValueInfo.viDate[1]) + ',' +
                  IntToStr(ValueInfo.viDate[2]);
        end;
      end;
    {String}
    PE_PF_STRING : sTmp := StrPas(ValueInfo.viString);
    {DateTime}
    PE_PF_DATETIME :  {YYYY,MM,DD HH:MM:SS}
      begin
        {Crystal's null datetime is -4713,1,1 0:0:0; Delphi does not
         allow for negative dates in it's TDateTime, so I use 1,1,1
instead}
        if ValueInfo.viDateTime[0] < 1 then
          sTmp := '1,1,1 1:1:1'
        else
        begin
          sTmp := IntToStr(ValueInfo.viDateTime[0]) + ',' +
                  IntToStr(ValueInfo.viDateTime[1]) + ',' +
                  IntToStr(ValueInfo.viDateTime[2]) + ' ' +
                  IntToStr(ValueInfo.viDateTime[3]) + ':' +
                  IntToStr(ValueInfo.viDateTime[4]) + ':' +
                  IntToStr(ValueInfo.viDateTime[5]);
        end;
      end;
    {Time}
    PE_PF_TIME :  {HH:MM:SS}
      begin
        {Crystal's null datetime is -4713,1,1 0:0:0; Delphi does not
         allow for zero times in it's TDateTime, so I use 1:1:1 instead}
        if ValueInfo.viTime[0] < 1 then
          sTmp := '1:1:1'
        else
        begin
          sTmp := IntToStr(ValueInfo.viTime[0]) + ':' +
                  IntToStr(ValueInfo.viTime[1]) + ':' +
                  IntToStr(ValueInfo.viTime[2]);
        end;
      end;
  end;
  Result := sTmp;
end;

{Removes the floating point from a numeric string}
function TruncStr (sValue: string): string;
var
  i : integer;
begin
  Result := '';
  i := Pos('.', sValue);
  if i > 0 then
    Result := Copy(sValue, 1, i-1);
end;

procedure SetParameterFields;
var
  ParameterInfo           : PEParameterFieldInfo;
  ParameterValueInfo      : PEParameterValueInfo;
  ValueInfo               : PEValueInfo;
  minValueInfo            : PEValueInfo;
  maxValueInfo            : PEValueInfo;
  startValueInfo          : PEValueInfo;
  endValueInfo            : PEValueInfo;
  nParams,
  nParam,
  nValues,
  nValue                  : smallint;
  iRangeInfo              : smallint;
  bShowDialog             : Bool;
begin
  ParameterInfo.structSize := SizeOf(PEParameterFieldInfo);
  ParameterValueInfo.structSize := SizeOf(PEParameterValueInfo);
  ValueInfo.structSize := SizeOf(PEValueInfo);
  minValueInfo.structSize := SizeOf(PEValueInfo);
  maxValueInfo.structSize := SizeOf(PEValueInfo);
  startValueInfo.structSize := SizeOf(PEValueInfo);
  endValueInfo.structSize := SizeOf(PEValueInfo);

  {Get the number of Parameter Fields}
  nParams := PEGetNParameterFields(PrintJob);
  if nParams = -1 then
    {Do Error Handler};

  {Turn off the Prompt Dialog: only turn on if needed}
  bShowDialog := PEGetAllowPromptDialog(PrintJob);
  if bShowDialog <> False then
  begin
    bShowDialog := Bool(False);
    if not PESetAllowPromptDialog(PrintJob, bShowDialog) then
      {Do Error Handler};
  end;

  {Loop through the Parameter Fields}
  for nParam := 0 to (nParams - 1) do
  begin
    if not PEGetNthParameterField(PrintJob, nParam, ParameterInfo) then
      {Do Error Handler};

    {Here we simulate passing a new value into the Parameter}
    {You would normally know in advance what type of Parameter you
     are dealing with, but we cover every type here...}
    ValueInfo.valueType := ParameterInfo.valueType;
    case ParameterInfo.valueType of
      {Number}
      PE_PF_NUMBER : ValueInfo.viNumber := 22;
      {Currency}
      PE_PF_CURRENCY : ValueInfo.viCurrency := 2.22;
      {Boolean}
      PE_PF_BOOLEAN : ValueInfo.viBoolean := True;
      {Date}
      PE_PF_DATE :  {YYYY,MM,DD}
        begin
          ValueInfo.viDate[0] := 1998;
          ValueInfo.viDate[1] := 10;
          ValueInfo.viDate[2] := 30;
        end;
      {String}
      PE_PF_STRING : StrPCopy(@ValueInfo.viString, 'New Value');
      {DateTime}
      PE_PF_DATETIME :  {YYYY,MM,DD HH:MM:SS}
        begin
          ValueInfo.viDateTime[0] := 1998;
          ValueInfo.viDateTime[1] := 10;
          ValueInfo.viDateTime[2] := 30;
          ValueInfo.viDateTime[3] := 12;
          ValueInfo.viDateTime[4] := 22;
          ValueInfo.viDateTime[5] := 32;
        end;
      {Time}
      PE_PF_TIME :  {HH:MM:SS}
        begin
          ValueInfo.viTime[0] := 12;
          ValueInfo.viTime[1] := 22;
          ValueInfo.viTime[2] := 32;
        end;
    end;

    {Parameter Prompt Value}
    StrPCopy(@ParameterInfo.Prompt, 'Enter a Value: ');

    {CurrentValueSet}
    {0 = Show Prompt Dialog, 1 = bypass Prompt Dialog}
    ParameterInfo.CurrentValueSet := 1;

    {DefaultValueSet}
    {1 = Show Prompt Dialog, 0 = bypass Prompt Dialog}
    ParameterInfo.DefaultValueSet := 0;

    case ParameterInfo.CurrentValueSet of
      0: {Default Value: change the prompt, but still prompt}
         begin
           {Convert ValueInfo to ParamFieldInfo DefaultValue}
           if not PEConvertVInfoToPFInfo(ValueInfo, ValueInfo.ValueType,
@ParameterInfo.DefaultValue) then
             {Do Error Handler};

           {Turn on PromptDialog}
           bShowDialog := Bool(True);
           if not PESetAllowPromptDialog(PrintJob, bShowDialog) then
             {Do Error Handler};
         end;

      1: {Current Value: pass in a new value, no parameter prompt}
         begin
           {Convert ValueInfo to ParamFieldInfo CurrentValue}
           if not PEConvertVInfoToPFInfo(ValueInfo, ValueInfo.ValueType,
@ParameterInfo.CurrentValue) then
             {Do Error Handler};
         end;
    end;

    {EditMask: Do not use EditMask and Min/Max limits at the same time,
they are mutually exclusive}
    StrPCopy(@ParameterInfo.EditMask, '');

    {isLimited: 1 is On, 0 is Off}
    ParameterInfo.isLimited := 1;

    {Should only set Min/Max if isLimited = 1}
    {Number, Currency, & String can be passed via PESetNthParameterField,
but Date, Time, and DateTime require PESetParameterMinMaxValue}
    if ParameterInfo.isLimited = 1 then
    begin
      minValueInfo.ValueType := ParameterInfo.valueType;
      maxValueInfo.ValueType := ParameterInfo.valueType;
      {Min/Max}
      case ParameterInfo.valueType of
        PE_PF_NUMBER :
          begin
            ParameterInfo.MinSize := 12;
            ParameterInfo.MaxSize := 25;
           end;
        PE_PF_CURRENCY :
          begin
            ParameterInfo.MinSize := 1.2;
            ParameterInfo.MaxSize := 2.5;
           end;
        PE_PF_STRING :
           begin
             ParameterInfo.MinSize := 5;
             ParameterInfo.MaxSize := 10;
           end;
        PE_PF_DATE :  {YYYY,MM,DD}
           begin
             minValueInfo.viDate[0] := 1997;
             minValueInfo.viDate[1] := 10;
             minValueInfo.viDate[2] := 30;
             maxValueInfo.viDate[0] := 1998;
             maxValueInfo.viDate[1] := 10;
             maxValueInfo.viDate[2] := 30;
             if not PESetParameterMinMaxValue(PrintJob,
@ParameterInfo.Name, @ParameterInfo.reportName, minValueInfo,
maxValueInfo) then
           end;
        {DateTime}
        PE_PF_DATETIME :  {YYYY,MM,DD HH:MM:SS}
           begin
             minValueInfo.viDateTime[0] := 1997;
             minValueInfo.viDateTime[1] := 10;
             minValueInfo.viDateTime[2] := 30;
             minValueInfo.viDateTime[3] := 12;
             minValueInfo.viDateTime[4] := 22;
             minValueInfo.viDateTime[5] := 32;
             maxValueInfo.viDateTime[0] := 1998;
             maxValueInfo.viDateTime[1] := 10;
             maxValueInfo.viDateTime[2] := 30;
             maxValueInfo.viDateTime[3] := 12;
             maxValueInfo.viDateTime[4] := 22;
             maxValueInfo.viDateTime[5] := 32;
             if not PESetParameterMinMaxValue(PrintJob,
@ParameterInfo.Name, @ParameterInfo.reportName, minValueInfo,
maxValueInfo) then
           end;
        {Time}
        PE_PF_TIME :  {HH:MM:SS}
           begin
             minValueInfo.viTime[0] := 01;
             minValueInfo.viTime[1] := 22;
             minValueInfo.viTime[2] := 32;
             maxValueInfo.viTime[0] := 12;
             maxValueInfo.viTime[1] := 22;
             maxValueInfo.viTime[2] := 32;
             if not PESetParameterMinMaxValue(PrintJob,
@ParameterInfo.Name, @ParameterInfo.reportName, minValueInfo,
maxValueInfo) then
           end;
      end;
    end;

    {Set the Parameter field}
    if not PESetNthParameterField(PrintJob, nParam, ParameterInfo) then
      {Do Error Handler};

    {Send Parameter Field Info}
    ParameterValueInfo.isNullable := 0;
    ParameterValueInfo.disallowEditing := 0;
    ParameterValueInfo.allowMultipleValues := 1; {True}
    ParameterValueInfo.hasDiscreteValues := 0;   {has Ranges}
    ParameterValueInfo.partOfGroup := 0;
    ParameterValueInfo.mutuallyExclusiveGroup := 0;
    ParameterValueInfo.groupNum := 0;
    if not PESetParameterValueInfo(PrintJob, @ParameterInfo.Name,
@ParameterInfo.ReportName, ParameterValueInfo) then
      {Do Error Handler};

    {Send DefaultValues: only required if the PromptDialog is going to
show}
    {You must use the ValueInfo structure to send in or change values.
See code above on how to do this}
    ValueInfo.ValueType := ParameterInfo.valueType;
    {Get Number of DefaultValues}
    nValues := PEGetNParameterDefaultValues(PrintJob,
@ParameterInfo.Name, @ParameterInfo.ReportName);
    if nValues = -1 then
      {Do Error Handler};

    {Loop through DefaultValues}
    for nValue := (nValues - 1) downto 0 do
    begin
      if not PEGetNthParameterDefaultValue(PrintJob,
@ParameterInfo.Name, @ParameterInfo.ReportName, nValue, ValueInfo) then
        {Do Error Handler};
      {If you want to change a DefaultValue, use PESetNth...}
      if not PESetNthParameterDefaultValue(PrintJob,
@ParameterInfo.Name, @ParameterInfo.ReportName, nValue, ValueInfo) then
        {Do Error Handler};
      {If you want to delete a DefaultValue, use PEDeleteNth...}
      if not PEDeleteNthParameterDefaultValue(PrintJob,
@ParameterInfo.Name, @ParameterInfo.ReportName, nValue) then
        {Do Error Handler};
    end;
    {If you want to add a DefaultValue, use PEAdd...}
    if not PEAddParameterDefaultValue(PrintJob, @ParameterInfo.Name),
@ParameterInfo.ReportName), ValueInfo) then
        {Do Error Handler};

    {Parameter Field CurrentValues/Ranges, only required if the Prompt
Dialog is not going to show but will be bypassed}
    if ParameterInfo.SetCurrentValue = 1 then
    begin
      {Parameter Field CurrentValues}
      if ParameterValueInfo.hasDiscreteValues = 1 then
      begin
        {If you want to change CurrentValues, you must first clear the
CurrentValues in the Report, then Add the values you want}
        if not PEClearParameterCurrentValuesAndRanges(PrintJob,
@ParameterInfo.Name, @ParameterInfo.ReportName) then
          {Do Error Handler};

        {Add CurrentValue}
        if not PEAddParameterCurrentValue(PrintJob, @ParameterInfo.Name,
@ParameterInfo.ReportName, ValueInfo) then
          {Do Error Handler};
      end
      {Parameter Field Ranges}
      else
      begin
        {If you want to change Ranges, you must first clear the Ranges in
the Report, then Add the values you want}
        if not PEClearParameterCurrentValuesAndRanges(PrintJob,
@ParameterInfo.Name, @ParameterInfo.ReportName) then
          {Do Error Handler};

        {You must use the ValueInfo structure to change ranges.  See code
above on how to do this}
        startValueInfo.valueType := ParameterInfo.valueType;
        endValueInfo.valueType := ParameterInfo.valueType;

        {RangeInfo can be one of the following options.  RangeInfo
determines if the Parameter Range available (for selecting records in the
Report) will include the start and end Range values or not}
        iRangeInfo := PE_RI_INCLUDEUPPERBOUND and
PE_RI_INCLUDELOWERBOUND;
        iRangeInfo := PE_RI_INCLUDELOWERBOUND;
        iRangeInfo := PE_RI_INCLUDEUPPERBOUND;
        iRangeInfo := PE_RI_NOUPPERBOUND and PE_RI_NOLOWERBOUND;

        {Add New Range settings}
        if not PEAddParameterCurrentRange(PrintJob, @ParameterInfo.Name,
@ParameterInfo.ReportName, startValueInfo, endValueInfo, iRangeInfo)
then
          {Do Error Handler};
      end;
    end;
  end;
end;


Delphi code for logging on/off a server

LogOnServer/LogOffServer do not require JobNumbers and therefore can be called before a PrintJob is opened.

Calls used
PELogOnServer
PELogOffServer
Code
uses CRDelphi;

procedure LogOnServer;
var
  LogInfo        : PELogOnInfo;
  pDllName       : array[0..255] of Char;
  sServerName,
  sDatabaseName,
  sUserId,
  sPassword
  sDllName       : string;
begin
  LogInfo.StructSize := SizeOf(PELogOnInfo);

  sServerName := 'oracleserver';
  sDatabaseName := ''; {not usually req'd for Oracle}
  sUserId := 'SCOTT';
  sPassword := 'tiger';
  sDllName := 'PDSODBC.DLL';

  {Populate the PELogOnInfo structure}
  StrPCopy(@LogInfo.ServerName, sServerName);
  StrPCopy(@LogInfo.DatabaseName, sDatabaseName);
  StrPCopy(@LogInfo.UserID, sUserId);
  StrPCopy(@LogInfo.Password, sPassword);
  StrPCopy(pDllName, UpperCase(sDllName));

  if not PELogOnServer(pDllName, LogInfo) then
    {Do Error Handler};
end;

procedure LogOffServer;
var
  LogInfo  : PELogOnInfo;
  pDllName : array[0..255] of Char;
begin
  LogInfo.StructSize := SizeOf(PELogOnInfo);

  sServerName := 'oracleserver';
  sDatabaseName := ''; {not usually req'd for Oracle}
  sUserId := 'SCOTT';
  sPassword := 'tiger';
  sDllName := 'PDSODBC.DLL';

  {Populate the PELogOnInfo structure}
  StrPCopy(@LogInfo.ServerName, sServerName);
  StrPCopy(@LogInfo.DatabaseName, sDatabaseName);
  StrPCopy(@LogInfo.UserID, sUserID);
  StrPCopy(@LogInfo.Password, sPassword);
  StrPCopy(pDllName, sDllName);

  if not PELogOffServer(pDllName, LogInfo) then
    {Do Error Handler};
end;


Delphi code for getting/setting table location

The code below assumes that a PrintJob is already open.

Calls used
PEGetNTables
PEGetNthTableLocation
PESetNthTableLocation
Code
uses CRDelphi;

procedure GetTableLocation;
var
  TableLoc     : PETableLocation;
  nTable       : smallint;
  nTables      : smallint;
  sName, sPath : string;
begin
  TableLoc.StructSize := SizeOf(PETableLocation);

  {Get number of tables}
  nTables := PEGetNTables(PrintJob);
  if nTables = -1 then
    {Do Error Handler};

  {Loop through the tables}
  for nTable := 0 to (nTables - 1) do
  begin
    {Get table location}
    if not PEGetNthTableLocation(PrintJob, nTable, TableLoc) then
      {Do Error Handler};

    sName := ExtractFileName(StrPas(@TableLoc.Location));
    sPath := ExtractFilePath(StrPas(@TableLoc.Location));
  end;
end;

{PESetNthTableLocation can be used to change the Table Path,
 Table Name, or both.  In this example the Path is changed}
procedure SetTableLocation;
var
  TableLoc     : PETableLocation;
  nTables      : smallint;
  nTable       : smallint;
  sName, sPath : string;
  sTmp         : string;
begin
  TableLoc.StructSize := SizeOf(PETableLocation);

  {Set New Path}
  sPath := 'C:\NewDir\';

  {Get the number of Tables}
  nTables := PEGetNTables(PrintJob);
  if nTables = -1 then
    {Do Error Handler};

  {Loop through the items}
  for nTable := 0 to (nTables - 1) do
  begin
    {Get table location}
    if not PEGetNthTableLocation(PrintJob, nTable, TableLoc) then
      {Do Error Handler};

    {Get the current Table Name}
    sName := ExtractFileName(StrPas(@TableLoc.Location));

    {Join the Current Table Name & New Path}
    sTmp := sPath + sName;

    {Send in the new Table location/name}
    StrPCopy(@TableLoc.Location, sTmp);
    if not PESetNthTableLocation(PrintJob, nTable, TableLoc) then
      {Do Error Handler};
  end;
end;


Delphi code for getting/setting formulas

The code below assumes that a PrintJob is already open.

Calls used
PEGetNFormulas
PEGetNthFormula
PESetNthFormula
PEGetFormula
PESetFormula
PECheckFormula
PEGetHandleString
Code
uses CRDelphi;

var
  slFormulas : TStringList;

{In this example, the Formula Names and Texts are stored to slFormulas, a
public StringList}
procedure GetFormulas;
var
  NameHandle  : hWnd;
  NameLength  : smallint;
  TxtHandle   : hWnd;
  TxtLength   : smallint;
  TxtBuffer   : PChar;
  nFormulas   : smallint;
  nFormula    : smallint;
begin
  {Get number of Formulas}
  nFormulas := PEGetNFormulas(PrintJob);
  if (nFormulas = -1) then
    {Do Error Handler};

  slFormulas := TStringList.Create;

  {Loop through the formulas}
  for nFormula := 0 to (nFormulas - 1) do
  begin
    NameLength := 0;
    TxtLength := 0;
    {Retrieve formula}
    if not PEGetNthFormula(PrintJob, nFormula, NameHandle, NameLength,
TxtHandle, TxtLength) then
      {Do Error Handler};

    {Get Formula Name}
    TxtBuffer := StrAlloc(NameLength);
    if not PEGetHandleString(NameHandle, TxtBuffer, NameLength) then
      {Do Error Handler};

    {Add a new Formula Name to StringList}
    slFormulas.Add(StrPas(TxtBuffer));

    {Get Formula Text}
    StrDispose(TxtBuffer);
    TxtBuffer := StrAlloc(TxtLength);
    if not PEGetHandleString(TxtHandle, TxtBuffer, TxtLength) then
      {Do Error Handler};

    {Add the Formula Text to the StringList Object}
    slFormulas.Objects[nFormula] := TStringList.Create;
    TStringList(slFormulas.Objects[nFormula]).SetText(TxtBuffer);
    StrDispose(TxtBuffer);
  end;
end;

{This procedure assumes we are using the public slFormulas StringList
which was filled with Formula information in the GetFormulas procedure
above}
procedure SetFormulas;
var
  sFormulaName : string;
  nTextLen     : smallint;
  hText        : hWnd;
  nFormulas    : smallint;
  nFormula     : smallint;
  pRptFormula  : PChar;
  Changed      : boolean;
  slTemp       : TStringList;
begin
  {Get the number of Formulas}
  nFormulas := PEGetNFormulas(PrintJob);
  if (nFormulas = -1) then
    {Do Error Handler};

  {Loop through the formulas}
  for nFormula := 0 to (nFormulas - 1) do
  begin
    Changed := False;

    {Get the Formula Name from the StringList created in GetFormulas}
    sFormulaName := slFormulas[nFormula];
    nTextLen := 0;

    {Retrieve the Formula currently in the Report}
    if not PEGetFormula(PrintJob, PChar(sFormulaName), hText, nTextLen)
then
      {Do Error Handler};

    {Get the Formula Text from the Report}
    pRptFormula := StrAlloc(nTextLen);
    if not PEGetHandleString(hText, pRptFormula, nTextLen) then
      {Do Error Handler};

    {Put the Report Formula Text into a StringList}
    slTemp := TStringList.Create;
    slTemp.SetText(pRptFormula);

    {Compare it to the new formula...If they are the same, do not send}
    if StrComp(TStringList(slFormulas.Objects[nFormula]).GetText,
slTemp.GetText) <> 0 then
       Changed := True;
    StrDispose(pRptFormula);
    slTemp.Free;

    {Send the Formula to the Report}
    if Changed then
    begin
      if not PESetFormula(PrintJob, PChar(sFormulaName),
TStringList(slFormulas.Objects[nFormula]).GetText) then
        {Do Error Handler};

      {Check the Formula}
      if not PECheckFormula(PrintJob, PChar(sFormulaName)) then
        {Do Error Handler};
    end;
  end;
end;

{Here is a procedure which shows how to free the memory allocated for the
slFormulas StringList}
procedure FreeFormulasList;
var
  cnt    : integer;
  slTemp : TStringList;
begin
  for cnt := (slFormulas.Count - 1) downto 0 do
  begin
    slTemp := TStringList(slFormulas.Objects[cnt]);
    slTemp.Free;
  end;
  slFormulas.Free;
end;


Delphi code for getting/setting print options

The code below assumes that a PrintJob is already open.

Calls used
PEGetPrintOptions
PESetPrintOptions
Code
uses CRDelphi;

var
  wStartPage,
  wStopPage,
  wCopies,
  wCollation      : Word;
  sOutputFileName : string;

procedure GetPrintOptions;
var
  PrintOpt : PEPrintOptions;
begin
  PrintOpt.StructSize := SizeOf(PEPrintOptions);

  if not PEGetPrintOptions(PrintJob, PrintOpt) then
    {Do Error Handler};

  wStartPage := PrintOpt.StartPageN;
  wStopPage := PrintOpt.StopPageN;
  wCopies := PrintOpt.nReportCopies;
  wCollation := PrintOpt.Collation;
  sOutputFileName := StrPas(@PrintOpt.outputFileName);
end;

{The SetPrintOptions procedure takes a parameter "PromptForOptions"
which shows how to use the Print Engine to prompt for PrintOptions}
procedure SetPrintOptions(PromptForOptions: boolean);
var
  PrintOpt   : PEPrintOptions;
  pPrintOpt  : ^PEPrintOptions;
  Changed    : boolean;
  sTmp       : string;
begin
  PrintOpt.StructSize := SizeOf(PEPrintOptions);

  pPrintOpt := nil;
  Changed := False;

  if PromptForOptions = True then
  begin
    {By passing in a Nil pointer, the Print Engine will prompt for
PrintOptions}
    if not PESetPrintOptions(PrintJob, PEPrintOptions(pPrintOpt^)) then
      {Do Error Handler};
    Exit;
  end;

  {Get PrintOptions from Report}
  if not PEGetPrintOptions(PrintJob, PrintOpt) then
    {Do Error Handler};

  {StartPage}
  if PrintOpt.StartPageN <> wStartPage then
  begin
    PrintOpt.StartPageN := wStartPage;
    Changed := True;
  end;

  {StopPage}
  if PrintOpt.StopPageN <> wStopPage then
  begin
    PrintOpt.StopPageN := wStopPage;
    Changed := True;
  end;

  {Copies}
  if PrintOpt.nReportCopies <> wCopies then
  begin
    PrintOpt.nReportCopies := wCopies;
    Changed := True;
  end;

  {Collation}
  if PrintOpt.Collation <> wCollation then
  begin
    PrintOpt.Collation := wCollation;
    Changed := True;
  end;

  {OutputFileName}
  sTmp := StrPas(@PrintOpt.outputFileName);
  if CompareText(sOutputFileName, sTmp) <> 0 then
  begin
    {OutputFileName cannot be larger than 512 characters}
    sTmp := Copy(sOutputFileName, 1, 512);
    StrPCopy(@PrintOpt.outputFileName, sTmp);
    Changed := True;
  end;

  {Send PrintOptions}
  if Changed then
  begin
    if not PESetPrintOptions(PrintJob, PrintOpt) then
      {Do Error Handler};
  end;
end;


Delphi code for getting/setting section format

The code below assumes that a PrintJob is already open.

Calls used
PEGetPrintOptions
Code
uses CRDelphi;

{Stringlists to store the Section Format information}
var
  sSuppress,
  sNewPageBefore,
  sNewPageAfter,
  sKeepTogether,
  sSuppressBlankSection,
  sResetPageNAfter,
  sPrintAtBottomOfPage,
  sUnderlaySection,
  sBackgroundColor,
  sFreeFormPlacement : TStringList;

procedure GetSectionFormat;
var
  SecOpt         : PESectionOptions;
  nSections,
  nSection       : smallint;
  nCode          : smallint;
begin
  SecOpt.structSize := SizeOf(PESectionOptions);

  {Get the # of Sections in the Report}
  nSections := PEGetNSections(PrintJob);
  if (nSections = -1) then
    {Do Error Handler};

  {Create storage StringLists}
  sSuppress              := TStringList.Create;
  sNewPageBefore         := TStringList.Create;
  sNewPageAfter          := TStringList.Create;
  sKeepTogether          := TStringList.Create;
  sSuppressBlankSection  := TStringList.Create;
  sResetPageNAfter       := TStringList.Create;
  sPrintAtBottomOfPage   := TStringList.Create;
  sUnderlaySection       := TStringList.Create;
  sFreeFormPlacement     := TStringList.Create;
  sBackgroundColor       := TStringList.Create;

  {Loop through the Sections}
  for nSection := 0 to (nSections - 1) do
  begin
    nCode := PEGetSectionCode(PrintJob, nSection);
    if not PEGetSectionFormat(PrintJob, nCode, SecOpt) then
      {Do Error Handler};

    case SecOpt.visible of
      0: sSuppress.Add('1');
      1: sSuppress.Add('0');
    end;
    sNewPageBefore.Add(IntToStr(SecOpt.newPageBefore));
    sNewPageAfter.Add(IntToStr(SecOpt.newPageAfter));
    sKeepTogether.Add(IntToStr(SecOpt.keepTogether));
    sSuppressBlankSection.Add(IntToStr(SecOpt.suppressBlankSection));
    sResetPageNAfter.Add(IntToStr(SecOpt.resetPageNAfter));
    sPrintAtBottomOfPage.Add(IntToStr(SecOpt.printAtBottomOfPage));
    sUnderlaySection.Add(IntToStr(SecOpt.underlaySection));
    sFreeFormPlacement.Add(IntToStr(SecOpt.freeFormPlacement));
    {Background Color}
    if SecOpt.backgroundColor = PE_NO_COLOR then
      sBackgroundColor.Add('-1')
    else
      sBackgroundColor.Add(IntToStr(SecOpt.backgroundColor));
  end;
end;

procedure SetSectionFormat;
var
  SecOpt             : PESectionOptions;
  nSection,
  nSections
  nCode              : smallint;
  nTmp1, nTmp2       : smallint;
  Changed            : boolean;
  nColor1, nColor2   : integer;
begin
  SecOpt.structSize := SizeOf(PESectionOptions);

  {Get the # of Sections in the Report}
  nSections := PEGetNSections(PrintJob);
  if (nSections = -1) then
    {Do Error Handler};

  {Loop through the Sections}
  for nSection := 0 to (nSections - 1) do
  begin
    Changed := False;
    nCode := PEGetSectionCode(PrintJob, nSection);
    if not PEGetSectionFormat(PrintJob, nCode, SecOpt) then
      {Do Error Handler};

    {Visible}
    nTmp1 := SecOpt.visible;
    try
      case StrToInt(sSuppress[nSection]) of
        0: nTmp2 := 1;  {translate "Suppress" to "Visible" by inverting}
        1: nTmp2 := 0;
        2: nTmp2 := 2;
      end;
    except
      nTmp2 := 2;
    end;
    if nTmp2 < 2 then
    begin
      if nTmp1 <> nTmp2 then
      begin
        SecOpt.visible := nTmp2;
        Changed := True;
      end;
    end;

    {NewPageBefore}
    nTmp1 := SecOpt.newPageBefore;
    try
      nTmp2 := StrToInt(sNewPageBefore[nSection]);
    except
      nTmp2 := 2;
    end;
    if nTmp2 < 2 then
    begin
      if nTmp1 <> nTmp2 then
      begin
        SecOpt.newPageBefore := nTmp2;
        Changed := True;
      end;
    end;

    {NewPageAfter}
    nTmp1 := SecOpt.newPageAfter;
    try
      nTmp2 := StrToInt(sNewPageAfter[nSection]);
    except
      nTmp2 := 2;
    end;
    if nTmp2 < 2 then
    begin
      if nTmp1 <> nTmp2 then
      begin
        SecOpt.newPageAfter := nTmp2;
        Changed := True;
      end;
    end;

    {KeepTogether}
    nTmp1 := SecOpt.keepTogether;
    try
      nTmp2 := StrToInt(sKeepTogether[nSection]);
    except
      nTmp2 := 2;
    end;
    if nTmp2 < 2 then
    begin
      if nTmp1 <> nTmp2 then
      begin
        SecOpt.keepTogether := nTmp2;
        Changed := True;
      end;
    end;

    {SuppressBlankSection}
    nTmp1 := SecOpt.suppressBlankSection;
    try
      nTmp2 := StrToInt(sSuppressBlankSection[nSection]);
    except
      nTmp2 := 2;
    end;
    if nTmp2 < 2 then
    begin
      if nTmp1 <> nTmp2 then
      begin
        SecOpt.suppressBlankSection := nTmp2;
        Changed := True;
      end;
    end;

    {ResetPageNAfter}
    nTmp1 := SecOpt.resetPageNAfter;
    try
      nTmp2 := StrToInt(sResetPageNAfter[nSection]);
    except
      nTmp2 := 2;
    end;
    if nTmp2 < 2 then
    begin
      if nTmp1 <> nTmp2 then
      begin
        SecOpt.resetPageNAfter := nTmp2;
        Changed := True;
      end;
    end;

    {PrintAtBottomOfPage}
    nTmp1 := SecOpt.printAtBottomOfPage;
    try
      nTmp2 := StrToInt(sPrintAtBottomOfPage[nSection]);
    except
      nTmp2 := 2;
    end;
    if nTmp2 < 2 then
    begin
      if nTmp1 <> nTmp2 then
      begin
        SecOpt.printAtBottomOfPage := nTmp2;
        Changed := True;
      end;
    end;

    {UnderlaySection}
    nTmp1 := SecOpt.underlaySection;
    try
      nTmp2 := StrToInt(sUnderlaySection[nSection]);
    except
      nTmp2 := 2;
    end;
    if nTmp2 < 2 then
    begin
      if nTmp1 <> nTmp2 then
      begin
        SecOpt.underlaySection := nTmp2;
        Changed := True;
      end;
    end;

    {FreeFormPlacement}
    nTmp1 := SecOpt.freeFormPlacement;
    try
      nTmp2 := StrToInt(sFreeFormPlacement[nSection]);
    except
      nTmp2 := 2;
    end;
    if nTmp2 < 2 then
    begin
      if nTmp1 <> nTmp2 then
      begin
        SecOpt.freeFormPlacement := nTmp2;
        Changed := True;
      end;
    end;

   {BackgroundColor}
   if SecOpt.backgroundColor = PE_NO_COLOR then
     nColor1 := -1
   else
     nColor1 := SecOpt.backgroundColor;
   try
     nColor2 := StrToInt(sBackgroundColor[nSection]);
   except
     nColor2 := PE_UNCHANGED_COLOR;
   end;
   if nColor2 <> PE_UNCHANGED_COLOR then
   begin
     if nColor1 <> nColor2 then
     begin
       SecOpt.backgroundColor := nColor2;
       Changed := True;
     end;
   end;

    {Send SectionFormat to Report}
    if Changed then
    begin
      if not PESetSectionFormat(PrintJob, nCode, SecOpt) then
        {Do Error Handler};
    end;
  end;
  {Free storage StringLists}
  sSuppress.Free;
  sNewPageBefore.Free;
  sNewPageAfter.Free;
  sKeepTogether.Free;
  sSuppressBlankSection.Free;
  sResetPageNAfter.Free;
  sPrintAtBottomOfPage.Free;
  sUnderlaySection.Free;
  sFreeFormPlacement.Free;
  sBackgroundColor.Free;
end;


Delphi code for getting/setting logon information

The code below assumes that a PrintJob is already open.

Calls used
  PEGetNTables
  PEGetNthTableType
  PEGetNthTableLogOnInfo
  PESetNthTableLogOnInfo
  PETestNthTableConnectivity
Code
uses CRDelphi;

{Stringlists to store the LogOn information}
var
  sServerName,
  sUserID,
  sPassword,
  sDatabaseName,
  {These last three are not necessary: they hold Table descriptive
information}
  sDLLName,
  sDescriptiveName,
  sTableType        : TStringList;

procedure GetLogOnInfo;
var
  LogInfo         : PELogOnInfo;
  TableType       : PETableType;
  nTables, nTable : smallint;
begin
  LogInfo.StructSize := SizeOf(PELogOnInfo);
  TableType.StructSize := SizeOf(PETableType);

  {Loop through the tables}
  nTables := PEGetNTables(PrintJob);
  if nTables = -1 then
    {Do Error Handler};

  {Create storage StringLists}
  sServerName       := TStringList.Create;
  sUserID           := TStringList.Create;
  sPassword         := TStringList.Create;
  sDatabaseName     := TStringList.Create;
  sDLLName          := TStringList.Create;
  sDescriptiveName  := TStringList.Create;
  sTableType        := TStringList.Create;

  {Loop through the tables}
  for nTable := 0 to (nTables - 1) do
  begin
    if not PEGetNthTableType(PrintJob, nTable, TableType) then
      {Do Error Handler};

    {Try to find an SQL table}
    if (TableType.DBType = PE_DT_SQL) or
       (TableType.DBType = PE_DT_SQL_STORED_PROCEDURE) then
    begin
      if not PEGetNthTableLogOnInfo(PrintJob, nTable, LogInfo) then
        {Do Error Handler};

      sServerName.Add(StrPas(@LogInfo.ServerName));
      sUserID.Add(StrPas(@LogInfo.UserID));
      {Password will be blank since it is not stored in the Report}
      sPassword.Add(StrPas(@LogInfo.Password));
      sDatabaseName.Add(StrPas(@LogInfo.DatabaseName));
      sDLLName.Add(StrPas(@TableType.DLLName));
      sDescriptiveName.Add(StrPas(@TableType.DescriptiveName));
      sTableType.Add(IntToStr(TableType.DBType));
    end;
  end;
end;

procedure SetLogOnInfo;
var
  LogInfo          : PELogOnInfo;
  nTable           : smallint;
  nTables          : smallint;
  nTable           : integer;
  sSN, sUID, sDBN  : string;
  Changed          : boolean;
begin
  LogInfo.StructSize := SizeOf(PELogOnInfo);
  nTable := 0;

  {Get number of tables}
  nTables := PEGetNTables(PrintJob);
  if nTables = -1 then
    {Do Error Handler};

  {Loop through the LogOnInfo items}
  for nTable := 0 to (nTables - 1) do
  begin
    Changed := False;
    {Get the LogOnInfo from the Report}
    if not PEGetNthTableLogOnInfo(PrintJob, nTable, LogInfo) then
      {Do Error Handler};

    {ServerName}
    sSN := StrPas(@LogInfo.ServerName);
    if CompareStr(sSN, sServerName[nTable]) <> 0 then
    begin
      if sServerName[nTable] <> '' then
        StrPCopy(@LogInfo.ServerName, sServerName[nTable]);
      Changed := True;
    end;

    {UserID}
    sUID := StrPas(@LogInfo.UserID);
    if CompareStr(sUID, sUserID[nTable]) <> 0 then
    begin
      if sUserID[nTable] <> '' then
        StrPCopy(@LogInfo.UserID, sUserID[nTable]);
      Changed := True;
    end;

    {Password}
    if sPassword[nTable] <> '' then
    begin
      StrPCopy(@LogInfo.Password, sPassword[nTable]);
      Changed := True;
    end;

    {DatabaseName}
    sDBN := StrPas(@LogInfo.DatabaseName);
    if CompareStr(sDBN, sDatabaseName[nTable]) <> 0 then
    begin
      if sDatabaseName[nTable] <> '' then
        StrPCopy(@LogInfo.DatabaseName, sDatabaseName[nTable]);
      Changed := True;
    end;

    {Send the LogOnInfo to the Report}
    if Changed then
    begin
      if not PESetNthTableLogOnInfo(PrintJob, nTable, LogInfo, False)
then
        {Do Error Handler};
    end;
  end;
  {Free storage StringLists}
  sServerName.Free;
  sUserID.Free;
  sPassword.Free;
  sDatabaseName.Free;
  sDLLName.Free;
  sDescriptiveName.Free;
  sTableType.Free;
end;

{LogOn Information can be tested before running a Report to confirm that
a connection can be established with the Server}
function TestLogOnInfo(nTable: smallint) : boolean;
var
  LogInfo : PELogOnInfo;
begin
  Result := False;
  LogInfo.StructSize := SizeOf(PELogOnInfo);

  StrPCopy(@LogInfo.ServerName, sServerName[nTable]);
  StrPCopy(@LogInfo.UserID, sUserID[nTable]);
  StrPCopy(@LogInfo.Password, sPassword[nTable]);
  StrPCopy(@LogInfo.DatabaseName, sDatabaseName[nTable]);

  {Set LogOnInfo}
  if not PESetNthTableLogOnInfo(PrintJob, nTable, LogInfo, False) then
    {Do Error Handler};

  {Test LogOn}
  Result := PETestNthTableConnectivity(PrintJob, nTable);
end;


Delphi code for getting/setting the SQL query

The code below assumes that a PrintJob is already open.

Calls used
  PEGetNTables,
  PEGetNthTableType,
  PESetNthTableLogOnInfo,
  PETestNthTableConnectivity,
  PEGetSQLQuery,
  PESetSQLQuery
  PEGetHandleString
Code
uses CRDelphi;

{Stringlists to store the LogOn information}
var
  sQuery : TStringList;

procedure GetSQLQuery;
var
  TableType       : PETableType;
  LogInfo         : PELogOnInfo;
  nTables, nTable : Smallint;
  hText           : hWnd;
  nTextLen        : smallint;
  pRptCurrent     : PChar;
begin
  TableType.StructSize := SizeOf(PETableType);
  LogInfo.StructSize := SizeOf(PELogOnInfo);

  {We must establish a Server connection before retrieving SQL Query}

  {Get # of Tables}
  nTables := PEGetNTables(PrintJob);
  if nTables = -1 then
    {Do Error Handler};

  {Loop through the tables}
  for nTable := 0 to (nTables - 1) do
  begin
    if not PEGetNthTableType(PrintJob, nTable, TableType) then
      {Do Error Handler};
    {Try to find a SQL table}
    if (TableType.DBType = PE_DT_SQL) or
       (TableType.DBType = PE_DT_SQL_STORED_PROCEDURE) then
    begin
      StrPCopy(@LogInfo.ServerName, 'SqlServerOne');
      StrPCopy(@LogInfo.UserID, 'James Bond');
      StrPCopy(@LogInfo.Password, '007');
      StrPCopy(@LogInfo.DatabaseName, 'pubs');
      {Set LogOnInfo, propagating across all tables}
      if not PESetNthTableLogOnInfo(PrintJob, nTable, LogInfo, True) then
        {Do Error Handler};

      {Test LogOn}
      if not PETestNthTableConnectivity(PrintJob, nTable) then
        {Do Error Handler};
      Break;
    end;
  end;

  {Get the SQL Query}
  nTextLen := 0;
  if PEGetSQLQuery(PrintJob, hText, nTextLen) then
  begin
    {Allocate memory for temporary PChar}
    pRptCurrent := StrAlloc(nTextLen);

    {Retrieve the Query from the handle}
    if (nTextLen > 1) then
    begin
      if not PEGetHandleString(hText, pRptCurrent, nTextLen) then
      begin
        StrDispose(pRptCurrent);
        {Do Error Handler};
      end;
      sQuery := TStringList.Create;
      sQuery.SetText(pRptCurrent);
    end;
    StrDispose(pRptCurrent);
  end;
end;

procedure SetSQLQuery;
begin
  {Send the Query}
  if not PESetSQLQuery(PrintJob, sQuery.GetText) then
  begin
    sQuery.Free;
    {Do Error Handler};
  end;
  {Free the Query StringList}
  sQuery.Free;
end;


Delphi code for exporting a report

The code below assumes that a PrintJob is already open. The ExportReport procedure takes three parameters: Export FileType, Export Destination, and a PromptForOptions boolean. Note that various other variables are used in the procedure which you may or may not use depending on the Export FileType and Destination specified. These are all listed below in the public variables section.

Calls used
  PEGetExportOptions
  PEExportTo
  PEStartPrintJob
Code
uses CRDelphi;

type
  TCrExportType = (Records, TabSeparated, Ascii, Dif, Csv,
CharacterSeparated,     TabSeparatedText, CrystalReportRPT, Excel2,
Excel3, Excel4, LotusWK1,     LotusWK3, LotusWKS, RTF, WordForWindows,
Excel5, HTML30, HTML32ext,     HTML32std, ODBCTable, PaginatedText,
Excel5Extended, ReportDefinition);

  TCrExportDestination = (toFile, toEmailViaMapi, toEmailViaVIM,
toMSExchange, toApplication);

var
  {FileName is required for all Exporting except when going to ODBCTable}
  FFileName              : string[255];
  {Number and Date format need to be specified when going to Records,
TabSeparated, Dif, Csv, CharacterSeparated}
  FUseRptNumberFmt       : boolean;
  FUseRptDateFmt         : boolean;
  {Quote and Separator need to be specified when going to
CharacterSeparated}
  FCharSepQuote          : string[1];
  FCharSepSeparator      : string[16];
  {These four need to be specified when going to ODBCTable}
  FODBCSource            : string;
  FODBCUser              : string;
  FODBCPassword          : string;
  FODBCTable             : string;
  {LinesPerPage needs to be specified when going to PaginatedText}
  FLinesPerPage          : Word;
  {These 5 need to be specified when going to Excel5Extended}
  FExcelColumnHeadings   : Bool;
  FExcelConstColumnWidth : Bool;
  FExcelConstant         : double;
  FExcelAreaCode         : smallint; {A SectionCode}
  FExcelTabularFormat    : Bool;
  {If Destination is toEmailViaMapi or toEmailViaVIM these must be filled
in}
  FEmailToList           : string;
  FEmailCCList           : string;
  FEmailVIMBCCList       : string;
  FEmailSubject          : string;
  FEmailMessage          : string;
  {If Destination is toMSExchange these must be filled in}
  FExchangeProfile       : string;
  FExchangePassword      : string;
  FExchangeFolder        : string;

procedure ExportReport(FileType: TCrExportType; Destination:
TCrDestination; PromptForOptions: boolean);
type
  TFormat = (DifFormat, Rec, CommaSep, CharSep, HTML, ODBCType,
     PagText, Xls5Ext);
const
  UXFFormatType: array[TCrExportType] of Word =(
    UXFRecordType, UXFTabSeparatedType, UXFTextType, UXFDifType,
    UXFCommaSeparatedType, UXFCharSeparatedType, UXFTabbedTextType,
    UXFCrystalReportType, UXFXls2Type, UXFXls3Type, UXFXls4Type,
    UXFLotusWk1Type, UXFLotusWk3Type, UXFLotusWksType,
UXFRichTextFormatType,
    UXFWordWinType, UXFXls5Type, UXFHTML3Type, UXFHTML32ExtType,
UXFHTML32StdType,
    UXFODBCType, UXFPaginatedTextType, UXFXls5TypeExt,
UXFReportDefinitionType);

  FormatDLL: array[TCrExportType] of string[12] =
   ('u2frec.dll', 'u2fsepv.dll', 'u2ftext.dll', 'u2fdif.dll',
'u2fsepv.dll',
    'u2fsepv.dll', 'u2ftext.dll', 'u2fcr.dll', 'u2fxls.dll',
'u2fxls.dll',
    'u2fxls.dll', 'u2fwks.dll', 'u2fwks.dll', 'u2fwks.dll',
'u2frtf.dll',
    'u2fwordw.dll', 'u2fxls.dll', 'u2fhtml.dll', 'u2fhtml.dll',
'u2fhtml.dll',
    'u2fodbc.dll', 'u2ftext', 'u2fxls.dll', 'u2frdef.dll');

  DestinationFormat: array[TCrExportDestination] of Word =
   (UXDDiskType, UXDMAPIType, UXDVIMType, UXDExchFolderType,
UXDApplicationType);

  DestinationDLL: array[TCrExportDestination] of string[12] =
   ('uxddisk.dll', 'uxdmapi.dll', 'uxdvim.dll', 'uxdpost.dll',
'uxdapp.dll');

var
  {Variables for Export: these must be in scope when StartPrintJob is
called.  If StartPrintJob is in another procedure, make these variables
public}
  ExportOpt    : PEExportOptions;
  {UXF: Format Options}
  UXFDif       : UXFDifOptions;
  UXFRec       : UXFRecordStyleOptions;
  UXFCsv       : UXFCommaTabSeparatedOptions;
  UXFCharSep   : UXFCharSeparatedOptions;
  UXFHTML      : UXFHTML3Options;
  UXFODBC      : UXFODBCOptions;
  UXFPagText   : UXFPaginatedTextOptions;
  UXFXls5Ext   : UXFXlsOptions;
  pFormat      : Pointer;
  {UXD: Disk Options}
  UXDDisk      : UXDDiskOptions;
  UXDMapi      : UXDMapiOptions;
  UXDVIM       : UXDVIMOptions;
  UXDExch      : UXDPostFolderOptions;
  UXDApp       : UXDApplicationOptions;
  pDisk        : Pointer;

  {Private FormatOptions function}
  function FormatOptions(const Key: TFormat): Pointer;
  var
    nCode  : integer;
    nGroup : integer;
  begin
    Result := nil;
    case Key of
      DifFormat:
        begin
          UXFDif.structSize := SizeOf(UXFDIFOptions);
          UXFDif.useReportNumberFormat := FUseRptNumberFmt;
          UXFDif.useReportDateFormat := FUseRptDateFmt;
          Result := @UXFDif;
        end;

      Rec:
        begin
          UXFRec.structSize := SizeOf(UXFRecordStyleOptions);
          UXFRec.useReportNumberFormat := FUseRptNumberFmt;
          UXFRec.useReportDateFormat := FUseRptDateFmt;
          Result := @UXFRec;
        end;

      CommaSep:
        begin
          UXFCsv.structSize := SizeOf(UXFCommaTabSeparatedOptions);
          UXFCsv.useReportNumberFormat := FUseRptNumberFmt;
          UXFCsv.useReportDateFormat := FUseRptDateFmt;
          Result := @UXFCsv;
        end;

      CharSep:
        begin
          UXFCharSep.structSize := SizeOf(UXFCharSeparatedOptions);
          UXFCharSep.useReportNumberFormat := FUseRptNumberFmt;
          UXFCharSep.useReportDateFormat := FUseRptDateFmt;
          UXFCharSep.stringDelimiter := FCharSepQuote[1];
          FCharSepSeparator := FCharSepSeparator + #0;
          UXFCharSep.fieldDelimiter := @FCharSepSeparator[1];
          Result := @UXFCharSep;
        end;

      HTML:
        begin
          UXFHTML.structSize := SizeOf(UXFHTML3Options);
          FFileName := FFileName + #0;
          UXFHTML.filename := @FFileName[1];
          Result := @UXFHTML;
        end;

      ODBCType:
        begin
          UXFODBC.structsize := SizeOf(UXFODBCOptions);
          FODBCSource := FODBCSource + #0;
          UXFODBC.dataSourceName := @FODBCSource[1];
          FODBCUser := FODBCUser + #0;
          UXFODBC.dataSourceUserID := @FODBCUser[1];
          FODBCPassword := FODBCPassword + #0;
          UXFODBC.dataSourcePassword :=  @FODBCPassword[1];
          FODBCTable := FODBCTable + #0;
          UXFODBC.exportTableName := @FODBCTable[1];
          Result := @UXFODBC
        end;

      PagText:
        begin
          UXFPagText.structSize := SizeOf(UXFPaginatedTextOptions);
          UXFPagText.nLinesPerPage := FLinesPerPage;
          Result := @UXFPagText;
        end;

      Xls5Ext:
        begin
          UXFXls5Ext.structSize := SizeOf(UXFXlsOptions);
          UXFXls5Ext.bColumnHeadings := FExcelColumnHeadings;
          UXFXls5Ext.bUseConstColWidth := FExcelConstColumnWidth;
          UXFXls5Ext.fConstColWidth := FExcelConstant;
          nCode := FExcelArea;
          nGroup := nCode mod 25;
          nCode := (nCode div 1000);
          UXFXls5Ext.baseAreaType := nCode;
          UXFXls5Ext.baseAreaGroupNum := nGroup + 1;
          UXFXls5Ext.bTabularFormat := Bool(FExcelTabularFormat);
          Result := @UXFXls5Ext;
        end;
    end;
  end; {FormatOptions}

  {Private DiskOptions function}
  function DiskOptions(const Key : TCrExportDestination) : Pointer;
  begin
    Result := nil;
    case Key of
      {Disk}
      toFile :
        begin
          UXDDisk.structSize := SizeOf(UXDDiskOptions);
          FFileName := FFileName + #0;
          UXDDisk.filename := @FFileName[1];
          Result := @UXDDisk;
        end;
      {MAPI}
      toEmailViaMapi :
        begin
          UXDMapi.structSize := SizeOf(UXDMAPIOptions);
          FEmailToList := FEmailToList + #0;
          UXDMapi.toList := @FEmailToList[1];
          FEmailCCList := FEmailCCList + #0;
          UXDMapi.ccList := @FEmailCCList[1];
          FEmailSubject := FEmailSubject + #0;
          UXDMapi.subject := @FEmailSubject[1];
          FEmailMessage := FEmailMessage + #0;
          UXDMapi.lpmessage := @FEmailMessage[1];
          Result := @UXDMapi;
        end;
      {VIM}
      toEMailViaVIM :
        begin
          UXDVIM.structSize := SizeOf(UXDVIMOptions);
          FEmailToList := FEmailToList + #0;
          UXDVIM.toList := @FEmailToList[1];
          FEmailCCList := FEmailCCList + #0;
          UXDVIM.bccList := @FEmailCCList[1];
          FEmailVIMBCCList := FEmailVIMBCCList + #0;
          UXDVIM.ccList := @FEmailVIMBCCList[1];
          FEmailSubject := FEmailSubject + #0;
          UXDVIM.subject := @FEmailSubject[1];
          FEmailMessage := FEmailMessage + #0;
          UXDVIM.lpmessage := @FEmailMessage[1];
          Result := @UXDVIM;
        end;
      {Exchange}
      toMSExchange :
        begin
          UXDExch.structsize := SizeOf(UXDPostFolderOptions);
          FExchangeProfile := FExchangeProfile + #0;
          UXDExch.pszProfile := @FExchangeProfile[1];
          FExchangePassword := FExchangePassword + #0;
          UXDExch.pszPassword := @FExchangePassword[1];
          FExchangeFolder := FExchangeFolder + #0;
          UXDExch.pszFolderPath := @FExchangeFolder[1];
          UXDExch.wDestType := 1011; {UXDPostDocMessage}
          Result := @UXDExch;
        end;
      {Application}
      toApplication :
        begin
          UXDApp.structSize := SizeOf(UXDApplicationOptions);
          FFileName := FFileName + #0;
          UXDApp.fileName := @FFileName[1];
          Result := @UXDApp;
        end;
    end;
  end; {DiskOptions}

{Main procedure: ExportReport}
begin
  ExportOpt.structSize := SizeOf(PEExportOptions);

  {The Print Engine can prompt for Export Options if desired}
  if PromptForOptions then
  begin
    if not PEGetExportOptions(PrintJob, ExportOpt) then
      {Do Error Handler};
  end
  else
  begin
    {Set FormatOptions}
    pFormat := nil;
    UXFCharSep.fieldDelimiter := nil;
    case FileType of
      Records                  : pFormat := FormatOptions(Rec);
      TabSeparated             : pFormat := FormatOptions(CommaSep);
      Ascii                    : pFormat := nil;
      Dif                      : pFormat := FormatOptions(DifFormat);
      Csv                      : pFormat := FormatOptions(CommaSep);
      CharacterSeparated       : pFormat := FormatOptions(CharSep);
      TabSeparatedText..Excel5 : pFormat := nil;
      HTML30..HTML32std        : pFormat := FormatOptions(HTML);
      ODBCTable                : pFormat := FormatOptions(ODBCType);
      PaginatedText            : pFormat := FormatOptions(PagText);
      Excel5Extended           : pFormat := FormatOptions(Xls5Ext);
      ReportDefinition         : pFormat := nil;
    end;
    StrPCopy(@ExportOpt.formatDLLName, FormatDLL[FileType]);
    ExportOpt.formatType := UXFFormatType[FileType];
    ExportOpt.formatOptions := pFormat;

    {Set DestinationOptions}
    pDisk := nil;
    if Destination = toApplication then
    begin
      StrPCopy(@ExportOpt.destinationDLLName,
DestinationDLL[Destination]{uxdapp});
      ExportOpt.destinationType :=
DestinationFormat[Destination]{UXDApplicationType};
      pDisk := DiskOptions(Destination);
      ExportOpt.destinationOptions := pDisk;
    end
    else
    begin
      StrPCopy(@ExportOpt.destinationDLLName,
DestinationDLL[Destination]);
      ExportOpt.destinationType := DestinationFormat[Destination];
      pDisk := DiskOptions(Destination);
      ExportOpt.destinationOptions := pDisk;
    end;
  end;

  {Send the ExportOptions to the Print Engine}
  if not PEExportTo(PrintJob, ExportOpt) then
    {Do Error Handler};

  {Start Exporting the Report}
  if not PEStartPrintJob(PrintJob, True) then
    {Do Error Handler};
end;


Crystal Report Engine Functions Sample Code in Visual Basic

The following examples cover most of the major functions of the Crystal Report Engine as well as some practical examples.

Click the appropriate link to jump to that section:

  • VB Sample Code for Print Only Link
  • VB Sample Code for Custom Print Link
  • VB Sample Code for Previewing a Report
  • VB Sample Code for converting from parameter field values
  • VB Sample Code for converting to parameter field values
  • VB Sample Code for exporting a report
  • VB Sample Code for handling errors
  • VB Sample Code for modifying database table settings
  • VB Sample Code for modifying formulas
  • VB Sample Code for modifying graphs
  • Appendix : VB Sample Code for modifying group conditions
  • VB Sample Code for modifying parameter fields
  • VB Sample Code for modifying section format formulas
  • VB Sample Code for modifying sections and lines
  • VB Sample Code for modifying selection formulas and group selection formulas
  • VB Sample Code for modifying SQL statements
  • VB Sample Code for modifying Subreports
  • VB Sample Code for modifying title, options, margins, and date
  • VB Sample Code for PEGetVersion
  • VB Sample Code for sorting groups
  • VB Sample Code for sorting records
  • VB Code for working with stored procedure parameters


VB Sample Code for Print Only Link

Printing to a Printer

Private Sub mnuPrintSimplePrint_Click()
        Dim result%

    ' When printing with PrintReport, no parameters are needed except the

      filename and print flag being set to true

    result% = PEPrintReport(lblReportName.Caption, True, 0, "", 0, 0, 0,
0,

    0, 0)

    If result% <> 0 Then

        MsgBox "Could not preview the report, check that the file name
and

        path are valid and that the file is a Crystal Reports file.",

        vbOKOnly + vbCritical, "Serious Error"

    End If

    MsgBox "Simple Print Complete!", vbOKOnly, "Operation Succeeded"

End Sub

Previewing the report in a window

Private Sub mnuPrintSimplePreview_Click()

    Dim result%, hwdPreview&

    ' In the Simple Print demonstration, there is no need to open and
close

      the report engine
    ' In the Simple Preview, if you don't open and close the report
engine

      manually, the preview window pops up and immediately disappears
again.
    ' In addition, if you open the engine, run the preview and
immediately

      close the engine the preview window will disappear.
    ' To delay the closing of the engine (and premature removal of the

      preview window) the Windows API calls GetActiveWindow and IsWindow
keep

      track of the existence of the preview window. As long as the
preview

      window exists, the report engine will not be closed. When the
preview

      window doesn't exist (ie - it has been closed), then the report
engine

      is closed.

    ' Opening the report engine - if something goes wrong, the program
cannot

      continue

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must
halt.",

        vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    ' The global constants for the preview window parameters are in

      SAMPLE.BAS

    ' Please refer to the custom-link preview function for additional

      information about preview windows

    result% = PEPrintReport(lblReportName.Caption, False, True, "Preview

    Window" & Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,

    CW_USEDEFAULT, WS_VISIBLE + WS_CAPTION + WS_BORDER + WS_SYSMENU +

    WS_THICKFRAME + WS_MINIMIZEBOX + WS_MAXIMIZEBOX, 0)

    ' Check to see if the preview succeeded - if it did, grab its handle

    If result% = 0 Then

        ' Get the handle to the active window, which will be the preview

          window

        hwdPreview& = GetActiveWindow()

        ' Loop as long as the preview window continues to exist

        ' DoEvents allows other programs to function (including the

          preview window)

        Do While IsWindow(hwdPreview&)

            DoEvents

        Loop

    Else

        MsgBox "Could not preview the report, check that the file name

        and path are valid and that the file is a Crystal Reports file.",

        vbOKOnly + vbCritical, "Serious Error"

    End If

    ' Close the report engine

    PECloseEngine

    MsgBox "Simple Print Preview Complete!", vbOKOnly, "Operation
Succeeded"

End Sub


VB Sample Code for Custom Print Link

Private Sub mnuPrintCustomPrint_Click()

    Dim result%, jobnum%, mainjob%, HasSavedData%, dialogflag%,
resultlong&

    Dim JobInfo As PEJobInfo, TempText$

    Dim PrintData As Printer

    Dim curprinter%, defprinterpos%

    Dim Mode As crDEVMODE

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",

        vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    ' Define size of JobInfo structure

    JobInfo.StructSize = PE_SIZEOF_JOB_INFO

    jobnum% = PEOpenPrintJob(lblReportName.Caption)

    ' Name from label on sample form

    ErrorTrap "OpenPrintJob in PrintCustom", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form,

    ' jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in PrintCustom", mainjob%

    End If

    ' If this is the pro edition, do the SavedData test

    result% = PEHasSavedData(jobnum%, HasSavedData%)

    ErrorTrap "HasSavedData in PrintCustom", jobnum%

    ' If there is saved data, give the user the option of using or

    ' discarding it

    If HasSavedData% <> 0 Then

        If MsgBox("There is data saved with this report. Would you like
to _

        refresh from the original data? Press Yes to refresh, No to use
the _

        saved data.", vbYesNo + vbQuestion, "Refresh Data?") = vbYes Then

            result% = PEDiscardSavedData(jobnum%)

            ErrorTrap "DiscardSavedData in PrintCustom", jobnum%

        End If

    End If

    If MsgBox("Do you want to see the progress dialog?", vbYesNo +
vbQuestion,

    "Display Progress Dialog?") = vbYes Then dialogflag% = True Else
dialogflag%

    = False

    result% = PEEnableProgressDialog(jobnum%, dialogflag%) ' Set whether
or not

    to display progress dialog

    ErrorTrap "EnabledProgressDialog in PrintCustom", jobnum%

    result% = PESetDialogParentWindow(jobnum%, Sample.hWnd) ' Set dialog
parent

    to main form

    ErrorTrap "SetDialogParentWindow in PrintCustom", jobnum%

    result% = PEOutputToPrinter(jobnum%, 1) ' Second value is number of
copies

    ErrorTrap "OutputtoPrinter in PrintCustom", jobnum%

    ' Selecting a printer using crPESelectPrinter

    ' crPESelectPrinter requires the printer, driver and port names for
the print

      device you wish to ' send a report to. This information is
available in the

      printers collection of VB4.

    ' The list of printers available on the system is displayed 1

    ' Modally on the SelectPrint form, along with an option to change the

      orientation of the print job.

    ' The orientation information is stored and passed in acrDEVMODE
structure.

     crDEVMODE structures can adjust the paper source, paper size and a
host of other features.

    Load SelectPrint

    CenterForm Sample, SelectPrint

    ' Loop through printers collection to load selectprint form with

      printer names

    For Each PrintData In Printers

        ' Add printer name and port to list

        SelectPrint!lstPrintList.AddItem PrintData.DeviceName & " at " &

        PrintData.Port

        ' Check for default printer

        If PrintData.DeviceName = Printer.DeviceName Then defprinterpos%
=

        SelectPrint!lstPrintList.NewIndex

    Next

    ' The list box on the SelectPrint form is positioned to the default
printer

      and then displayed 1 ' Modally

    SelectPrint!lstPrintList.ListIndex = defprinterpos%

    SelectPrint.Show 1 ' Modal

    ' When execution returns, one of the buttons on the SelectPrint form
has been

      pressed. The Select Case statement determines which

    Select Case SelectPrint.Tag

        Case "Print"

            ' Get which printer was selected from the list

            curprinter% = SelectPrint!lstPrintList.ListIndex

            ' Set crDEVMODE to whichever orientation was selected on the
form

            If SelectPrint!optPortrait.Value = True Then

                mode.dmOrientation = DMORIENT_PORTRAIT

            Else

                mode.dmOrientation = DMORIENT_LANDSCAPE

            End If

            ' NOTE - the dmFields element of the crDEVMODE structure must
contain

              what elements of the crDEVMODE

            ' structure are being used. To set multiple elements, use the
OR

              statement to combine the elements together

            ' In this example, only the orientation element is being set.

            mode.dmFields = DM_ORIENTATION

            ' Do the SelectPrinter call

            result% = crPESelectPrinter(jobnum%,
Printers(curprinter%).DriverName,

            Printers(curprinter%).DeviceName, Printers(curprinter%).Port,

            mode)

            ErrorTrap "SelectPrinter in PrintCustom", jobnum%

            ' Print the job

            result% = PEStartPrintJob(jobnum%, True)

            ' Note that flag must ALWAYS be true - setting to false will
yield

              unpredictable results

            ErrorTrap "StartPrintJob in PrintCustom", jobnum%

        Case "Cancel"

            MsgBox "Cancel was pressed on the Select Printer form. The
report

            will not be printed.", vbOKOnly + vbInformation, "Cancel
Pressed"

    End Select

    ' Unload the SelectPrint form

    Unload SelectPrint

    ' Get job status information and display it

    result% = PEGetJobStatus(jobnum%, JobInfo)

    ErrorTrap "GetJobStatus in PrintCustom", jobnum%

    ' Build status string based on results from job status call

    Select Case result%

        Case PE_JOBNOTSTARTED

            TempText$ = "Job Not Started"

        Case PE_JOBINPROGRESS

            TempText$ = "Job In Progress"

        Case PE_JOBCOMPLETED

            TempText$ = "Job Completed"

        Case PE_JOBFAILED

            TempText$ = "Job Failed"

        Case PE_JOBCANCELLED

            TempText$ = "Job Cancelled"

    End Select

    TempText$ = "Job Status: " & TempText$ & Chr$(10)

    TempText$ = TempText$ & "Records Read: " & JobInfo.NumRecordsRead &
Chr$(10)

    TempText$ = TempText$ & "Records Selected: " &
JobInfo.NumRecordsSelected &

    Chr$(10)

    TempText$ = TempText$ & "Records Printed: " &
JobInfo.NumRecordsPrinted &

    Chr$(10)

    TempText$ = TempText$ & "Display Page Num: " & JobInfo.DisplayPageN &

    Chr$(10)

    TempText$ = TempText$ & "Latest Page Num: " & JobInfo.LatestPageN &
Chr$(10)

    TempText$ = TempText$ & "Starting Page Num: " & JobInfo.StartPageN &
Chr$(10)

    TempText$ = TempText$ & IIf(JobInfo.PrintEnded, "Print has ended.",
"Print

    has not ended.")

    ' Display results and stats for job

    MsgBox TempText$, vbOKOnly, "Job Status"

    ' Subreport check - if a subreport is currently open, call
PreviewReport to

      offer a chance to preview the main report, then close the subreport
and

      main report

    If lblSubreportName.Visible Then

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in PrintCustom", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Custom-Link Print Complete!", vbOKOnly, "Operation Succeeded"

End Sub

ActiveX

Private Sub mnuPrintPrint_Click()

    CrystalReport1.ReportFileName = lblReportName.Caption

    ' Name from label on sample form

    ' Discard saved data?

    If MsgBox("Do you wish to discard any saved data?", vbYesNo +
vbQuestion,

    "Discard Saved Data?") = vbYes Then

        CrystalReport1.DiscardSavedData = 1

    End If

    ' Display progress dialog?

    If MsgBox("Do you want to see the progress dialog?", vbYesNo +
vbQuestion,

    "Display Progress Dialog?") = vbYes Then

        CrystalReport1.ProgressDialog = True

    Else

        CrystalReport1.ProgressDialog = False

    End If

    CrystalReport1.Destination = 1 ' Printer

    ' Display Windows printer selection dialog

    CrystalReport1.PrinterSelect

    ' Print

    CrystalReport1.Action = 1

    MsgBox "Print Complete!", vbOKOnly, "Operation Completed"

End Sub


VB Sample Code for Previewing a Report

Private Sub mnuPrintCustomPreview_Click()

    Dim result%, jobnum%, mainjob%, printcontrols%

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",

        vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Filename from label
on

    Sample form

    ErrorTrap "OpenPrintJob in PrintPreview", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form,

      jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in PrintPreview", mainjob%

    End If

    ' While you can specify exact values for the left, top, width and
height of

      the Preview form, in most cases you'll want to use the default
values,

      which scale appropriately for the system being used and the report

    ' These global constants are in the SAMPLE.BAS file

    result% = PEOutputToWindow(jobnum%, "Crystal Reports Preview" &
Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
WS_VISIBLE + WS_CAPTION + WS_BORDER + WS_SYSMENU + WS_THICKFRAME +
WS_MINIMIZEBOX + WS_MAXIMIZEBOX, Sample.hWnd)

    ErrorTrap "OutputtoWindow in PrintPreview", jobnum%

    ' Before the print job begins, disable the menu items that would
cause

      trouble

    mnuFileOpen.Enabled = False

    mnuFileClose.Enabled = False

    mnuFileSubReport.Enabled = False

    mnuPrint.Enabled = False

    mnuSorting.Enabled = False

    mnuEdit.Enabled = False

    mnuFormat.Enabled = False

    mnuTableSQL.Enabled = False

    result% = PEStartPrintJob(jobnum%, True) ' True indicates wait until
job is

    finished before proceeding

    ErrorTrap "StartPrintJob in PrintPreview", jobnum%

    ' Once the job has started, you must delay closing the job until the
user has

    ' finished viewing the preview window. By monitoring the existence of
a

      handle

    ' for the preview window, execution will proceed when the window is

      destroyed.

    ' ie - when the user has finished examining the report and pressed
close or

      print

    result% = 1

    Do While result% <> 0

        ' If a pro edition, we can create our own preview controls, and
not use

          the Crystal ones

        ' If the print controls are showing, get rid of them, and show the

        ' PreviewButtons form

        result% = PEPrintControlsShowing(jobnum%, printcontrols%)

        ErrorTrap "PrintControlsShowing in PrintPreview", jobnum%

        If printcontrols% = 1 Then

            printcontrols% = 0

            result% = PEShowPrintControls(jobnum%, printcontrols%)

            ErrorTrap "ShowPrintControls in PrintPreview", jobnum%

            Load PreviewButtons

            CenterForm Sample, PreviewButtons

            PreviewButtons.Show

        End If

        ' Check for any button presses - pressing a button loads the form
tag

        ' with the name of the button

        if Len(PreviewButtons.Tag) <> 0 Then

            Select Case PreviewButtons.Tag

                Case "Last Page"

                    result% = PEShowLastPage(jobnum%)

                Case "Prev Page"

                    result% = PEShowPreviousPage(jobnum%)

                Case "Next Page"

                    result% = PEShowNextPage(jobnum%)

                Case "First Page"

                    result% = PEShowFirstPage(jobnum%)

                Case "Goto Page"

                    ' Before going to a page, check to see if the page
number

                    ' is valid

                    ' Find the maximum page number first

                    printcontrols% = PEGetNPages(jobnum%)

                    ErrorTrap "GetNPages in PrintPreview", jobnum%

                    ' If the page number entered is less than 1, set it
to 1

                    If Val(PreviewButtons!txtPage.Text) < 1 Then

                        PreviewButtons!txtPage.Text = "1"

                        ' Otherwise, if its greater than the maximum page
number,

                          set it to that

                    ElseIf Val(PreviewButtons!txtPage.Text) >
printcontrols% Then

                        PreviewButtons!txtPage.Text = printcontrols%

                    End If

                    ' Get the page number the user wishes to go to and set
it

                    printcontrols% = Val(PreviewButtons!txtPage.Text)

                    result% = PEShowNthPage(jobnum%, printcontrols%)

                Case "Next Zoom"

                    result% = PENextPrintWindowMagnification(jobnum%)

                Case "Set Zoom"

                    ' Set Zoom can be set using 25-400% or default values

                    ' from the radio buttons on the form

                    ' First check if there is a value in the Zoom
percentage,

                      and if there is, make it valid

                    ' By confining its range to 25-400

                    If Len(Trim(PreviewButtons!txtZoom.Text)) <> 0 Then

                        If Val(PreviewButtons!txtZoom.Text) < 25 Then

                            PreviewButtons!txtZoom.Text = "25"

                        ElseIf Val(PreviewButtons!txtZoom.Text) > 400 Then

                            PreviewButtons!txtZoom.Text = "400"

                        End If

                        printcontrols% = Val(PreviewButtons!txtZoom.Text)

                        ' If there isn't a value in the Zoom percentage
text box,

                        ' use the radio buttons

                    ElseIf PreviewButtons!optZoom(0).Value Then

                        printcontrols% = PE_ZOOM_FULL_SIZE

                    ElseIf PreviewButtons!optZoom(1).Value Then

                        printcontrols% = PE_ZOOM_SIZE_FIT_ONE_SIDE

                    ElseIf PreviewButtons!optZoom(2).Value Then

                        printcontrols% = PE_ZOOM_SIZE_FIT_BOTH_SIDES

                    End If

                    ' printcontrols has the appropriate value for the
zoom,

                    ' now set the zoom

                    result% = PEZoomPreviewWindow(jobnum%, printcontrols%)

                Case "Print"

                    result% = PEPrintWindow(jobnum%, True)

                Case "Export"

                    result% = PEExportPrintWindow(jobnum%, False, True)

                Case "Close"

                    PECloseWindow jobnum%

            End Select

            ' This error trap covers the last call (in most cases, the
only

            ' call) in the select case list

            ErrorTrap PreviewButtons.Tag & " Button press in
PrintPreview", _

                jobnum%

            ' Clear the tag for the next button press

            PreviewButtons.Tag = ""

        End If

        DoEvents

        result% = PEGetWindowHandle(jobnum%)

    Loop

    ' Whether its loaded or not, make sure the PreviewButtons form is
unloaded

    Unload PreviewButtons

    ' Restore the menu items

    mnuFileOpen.Enabled = True

    mnuFileClose.Enabled = True

    mnuFileSubReport.Enabled = True

    mnuPrint.Enabled = True

    mnuSorting.Enabled = True

    mnuEdit.Enabled = True

    mnuFormat.Enabled = True

    mnuTableSQL.Enabled = True

    ' Subreport check - if a subreport is currently open, call
PreviewReport to

      offer a chance to preview the main report, then close the subreport
and

      main report

    If lblSubreportName.Visible Then

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in PrintPreview", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Preview Complete!", vbOKOnly, "Operation Succeeded"

End Sub

ActiveX

Private Sub mnuPrintPreview_Click()

    Dim hwndPreviewWindow As Long

    CrystalReport1.ReportFileName = lblReportName.Caption ' Name from
label

    on sample form

    CrystalReport1.Destination = 0 ' Window

    ' Set Output Window parameters

    CrystalReport1.WindowBorderStyle = 2 ' Sizable

    CrystalReport1.WindowControlBox = True

    CrystalReport1.WindowControls = True

    CrystalReport1.WindowMaxButton = True

    CrystalReport1.WindowMinButton = True

    CrystalReport1.WindowState = 0 ' Normal

    CrystalReport1.WindowTitle = "Crystal Reports 5.0 Preview"

    CrystalReport1.WindowHeight = 500

    CrystalReport1.WindowWidth = 500

    CrystalReport1.WindowTop = 100

    CrystalReport1.WindowLeft = 100

    CrystalReport1.Action = 1 ' Print

    ' Get handle for preview window (should be the active window, it will
have

      been just created)

    hwndPreviewWindow = GetActiveWindow()

    ' Keep checking that the handle is still valid - as long as it is,
the Window

      still exists

    ' and execution is stopped

    PreviewButtons.Show

    Do While IsWindow(hwndPreviewWindow)

        DoEvents

        If Len(PreviewButtons.Tag) <> 0 Then

            Select Case PreviewButtons.Tag

                Case "Last Page"

                    CrystalReport1.PageLast

                Case "Prev Page"

                    CrystalReport1.PagePrevious

                Case "Next Page"

                    CrystalReport1.PageNext

                Case "First Page"

                    CrystalReport1.PageFirst

                Case "Goto Page"

                    CrystalReport1.PageShow
(Val(PreviewButtons!txtPage.Text))

                Case "Zoom"

                    CrystalReport1.PageZoom
(Val(PreviewButtons!txtZoom.Text))

            End Select

            PreviewButtons.Tag = ""

        End If

    Loop

    Unload PreviewButtons

    ' Close the report

    CrystalReport1.ReportFileName = ""

    MsgBox "Preview Complete!", vbOKOnly, "Operation Completed"

End Sub


VB Sample Code for converting from parameter field values

Dim valueInfo As PEValueInfo

Dim info As PEParameterFieldInfo

info.StructSize = PE_SIZEOF_PARAMETER_FIELD_INFO

valueInfo.StructSize = PE_SIZEOF_VALUE_INFO

If PEGetNthParameterField(job, 0, info.ValueType, info.DefaultValueSet,
info.CurrentValueSet, info.Name, info.Prompt, info.DefaultValue,
info.CurrentValue) = 0 Then

        getError

Else

        If (PEConvertPFInfoToVInfo(info.DefaultValue,   info.valueType,
valueInfo) = 0 Then

        getError

    Else

        'if parameter 0 was type...    Then value is now in...

        'Number                info.viNumber

        'Currency                info.viCurrency

        'Boolean                info.viBoolean

        'String                info.viString

        'Date                    info.viDate[0] = year

        '                    info.viData[1] = month

        '                    info.viDate[2] = day

        '

    End If

End If


VB Sample Code for converting to parameter field values

Dim valueInfo As PEValueInfo

Dim info As PEParameterFieldInfo

info.StructSize = PE_SIZEOF_PARAMETER_FIELD_INFO

valueInfo.StructSize = PE_SIZEOF_VALUE_INFO

If PEGetNthParameterField(job, 0, info.ValueType, info.DefaultValueSet,
info.CurrentValueSet, info.Name, info.Prompt, info.DefaultValue,
info.CurrentValue) = 0 Then

    getError

Else

    Select Case info.valueType

            Case PE_PF_NUMBER

                valueInfo.viNumber = 42.69

            Case PE_PF_CURRENCY

                valueInfo.viCurrency = 995532.26

            Case PE_PF_BOOLEAN

                valueInfo.viBoolean = 1

            Case PE_PF_STRING

                valueInfo.viString = "Later Yesterday" + Chr(0)

            Case PE_PF_DATE

                valueInfo.viDate(0) = 1997

                valueInfo.viDate(1) = 5

                valueInfo.viDate(2) = 1

        End Select

        valueInfo.valueType = info.valueType

        If PEConvertVInfoToPFInfo(valueInfo, info.valueType,
info.CurrentValue) = 0 Then

            getError

        Else

            info.CurrentValueSet = 1

            If PESetNthParameterField(jobnum%,
Sections!lstSections.ListIndex, info.ValueType, info.DefaultValueSet,
info.CurrentValueSet, info.Name, info.Prompt, info.DefaultValue,
info.CurrentValue) = 0 Then

                getError

            End If

        End If

End If


VB Sample Code for exporting a report

Exporting reports using the Crystal Reports Print Engine in Visual Basic has caused a problem for several developers. This is not so much a problem with Crystal Reports or Visual Basic, but instead, is an issue on how memory allocation is handled by each application. To understand why this causes a problem, we must look at how the PEExportOptions structure is declared in C and in Visual Basic.

The C declaration for the PEExportOptions structure is as follows:

typedef struct PEExportOptions
{
    WORD StructSize;
    char formatDLLName [PE_DLL_NAME_LEN];
    DWORD formatType;
    void FAR *formatOptions;
    char destinationDLLName [PE_DLL_NAME_LEN];
    DWORD destinationType;
    void FAR *destinationOptions;
    // Following 2 member are Set by PEGetExportOptions, but ignored by
PEExportTo
    WORD nFormatOptionsBytes;
    WORD nDestinationOptionsBytes;
} PEExportOptions;

Since Visual Basic does not support pointers as data members of structures, the equivalent of "void FAR *" is "Long"

The Visual Basic declaration for the same structure is as follows:

Type PEExportOptions
    StructSize As Integer
    FormatDLLName As String * PE_DLL_NAME_LEN
    FormatType As Long
    FormatOptions As Long
    DestinationDLLName As String * PE_DLL_NAME_LEN
    DestinationType As Long
    DestinationOptions As Long
    ' Following 2 member are Set by PEGetExportOptions, but ignored by
PEExportTo
    NFormatOptionsBytes As Integer
    NDestinationOptionsBytes As Integer
End Type

The FormatOptions and DestinationOptions members of the PEExportOptions structure, depending on the format and destination selected, will point to different structures (ie. DiskOptions, MAPIOptions, etc). There is no easy way to get the address for any variable in Visual Basic. This means that structures with members that are pointers cannot be used in Visual Basic. This problem exists in 16 and 32bit Visual Basic, but the problem is more severe in 32bit. The Crystal Reports Print Engine ( CRPE32.DLL) uses 1-byte alignment. Visual Basic 32bit uses 4-byte alignment.

In the example below, assume that each space between a vertical separator is a byte. Assume that X and Y are members of the PEExportOptions structure. Now assume that X takes up 2 bytes and Y takes up 2 bytes:

1-byte alignment (CRPE.DLL / CRPE32.DLL)

|X |X |Y |Y |   |   |   |   |

4-byte alignment (Visual Basic)

|X |X |   |   |Y |Y |   |   |

Notice the space in the 4-byte alignment. This is how memory looks when a variable is declared in Visual Basic of type PEExportOptions. When the structure is passed to the Crystal Reports Engine, the Report Engine expects Y to be immediately after X, but as this is not the case, the values being set for exporting the report are not accurate and as a result, will fail.

There is good news. Crystal Reports has created a "Wrapper" DLL (Dynamic Link Library) that bypasses Visual Basic and allows the Report Engine to fill in the values for the PEExportOptions structure. This DLL did not exist prior to version 4.5. The DLL names in existing versions of Crystal Reports are as follows:

  9. Download wrapper.zip and follow the readme.txt for usage

4.5 32bit "Vbexpt32.dll" (Download from web site, developed after Crystal Reports 4.5 shipped)

http://support.seagatesoftware.com/updates

  10. Click on the patches/updates link on the orange menu bar.
  11. Click on BBS files (FTP Link) link
  12. Click on 32bit link
  13. Download vbexp32.zip and follow the readme.txt for usage

5.0 16bit "Crwrap16.dll" (Shipped with Crystal Reports 5.0)

5.0 32bit "Crwrap32.dll" (Shipped with Crystal Reports 5.0)

6.0 16bit "Crwrap16.dll" (Shipped with Crystal Reports 6.0)

6.0 32bit "Crwrap32.dll" (Shipped with Crystal Reports 6.0)

If you are using Crystal Reports 4.5 16bit, include "wrapper.bas" in your Visual Basic project. If you are using 4.5 32bit Crystal Reports, include "vbexpt32.bas" in your Visual Basic project. If you are using Crystal Reports version 5.0 or higher, include "crwrap.bas" in your Visual Basic project.

Exporting using the Wrapper DLL is broken into the following API calls. These API calls are not found in any help file and are only documented in the "*.bas" file that you include in your project as mentioned above. The function declarations for these API calls and the format type constants are included in the "*.bas" file.

crPEExportToDisk - Exporting to Disk file
crPEExportToMAPI - Exporting to Mail (MAPI)
crPEExportToEXCH - Exporting to Microsoft Exchange
crPEExportToODBC - Exporting to an ODBC data source
crPEExportToHTML - Exporting to HTML format

Note: Any strings being passed to these functions MUST be NULL terminated.

Here is some sample code from a Visual Basic application that demonstrates how to export using these wrapper functions. Note that you don't have to fill in each variable specified, since some variables are specific to the format being exported to. The case numbers used for ExportFormat and ExportDestination are specific to this example, and are used in this manner for clarity. You can change these values if you desire.

Dim Result As Integer
Dim MainJob As Integer
Dim ExportFormat As Integer
Dim ExportDestination As Integer
Dim FormatDLLName As String
Dim FormatType As Long
Dim UseSameNumberFormat As Integer
Dim UseSameDateFormat As Integer
Dim StringDelimiter As String
Dim FieldDelimiter As String
Dim DataSource As String
Dim UserID As String
Dim Password As String
Dim TableName As String
Dim MAPIToList As String
Dim MAPICCList As String
Dim MAPISubject As String
Dim MAPIMessage As String
Dim EXCHProfile As String
Dim EXCHPassword As String
Dim EXCHFolderPath As String

ExportFormat = Select an export format
ExportDestination = Select an export destination

DataSource = ODBC data source name
UserID = Logon user id
Password = Logon password
TableName = Table name to export data to

UseSameNumberFormat = 1 or 0 for True or False
UseSameDateFormat = 1 or 0 for True or False
StringDelimiter = String delimiter for character separated value format
FieldDelimiter = Field delimiter for character separated value format

MAPIToList = Email To list
MAPICCList = Email CC list
MAPISubject = Email subject
MAPIMessage = Email message

EXCHProfile = Exchange profile
EXCHPassword = Exchange password
EXCHFolderPath = Exchange folder path

' Open print engine
Result = PEOpenEngine()
' Open the selected report
MainJob = PEOpenPrintJob("c:\myreport.rpt" & vbNullChar)
' Set FormatDLLName and FormatType based on selected format type
Select Case ExportFormat
    Case 0    ' Crystal Reports
        FormatDLLName = "uxfcr.dll"        ' "u2fcr.dll" for 32bit
        FormatType = crUXFCrystalReportType
    Case 1    ' Data Interchange
        FormatDLLName = "uxfdif.dll"        ' "u2fdif.dll" for 32bit
        FormatType = crUXFDIFType
    Case 2    ' Word for Windows
        FormatDLLName = "uxfwordw.dll"    ' "u2fwordw.dll" for 32bit
        FormatType = crUXFWordWinType
    Case 3    ' Record Style
        FormatDLLName = "uxfrec.dll"        ' "u2frec.dll" for 32bit
        FormatType = crUXFRecordType
    Case 4    ' Rich Text
        FormatDLLName = "uxfrtf.dll"        ' "u2frtf.dll" for 32bit
        FormatType = crUXFRichTextFormatType
    Case 5    ' Comma Separated Values
        FormatDLLName = "uxfsepv.dll"        ' "u2fsepv.dll" for 32bit
        FormatType = crUXFCommaSeparatedType
    Case 6    ' Tab Separated Values
        FormatDLLName = "uxfsepv.dll"        ' "u2fsepv.dll" for 32bit
        FormatType = crUXFTabSeparatedType
    Case 7    ' Character Separated Values
        FormatDLLName = "uxfsepv.dll"        ' "u2fsepv.dll" for 32bit
        FormatType = crUXFCharSeparatedType
    Case 8    ' Text
        FormatDLLName = "uxftext.dll"        ' "u2ftext.dll" for 32bit
        FormatType = crUXFTextType
    Case 9    ' Paginated Text
        FormatDLLName = "uxftext.dll"        ' "u2ftext.dll" for 32bit
        FormatType = crUXFPaginatedTextType
    Case 10    ' Tab Separated Text
        FormatDLLName = "uxftext.dll"        ' "u2ftext.dll" for 32bit
        FormatType = crUXFTabbedTextType
    Case 11    ' Lotus WKS
        FormatDLLName = "uxfwks.dll"        ' "u2fwks.dll" for 32bit
        FormatType = crUXFLotusWksType
    Case 12    ' Lotus WK1
        FormatDLLName = "uxfwks.dll"        ' "u2fwks.dll" for 32bit
        FormatType = crUXFLotusWk1Type
    Case 13    ' Lotus WK3
        FormatDLLName = "uxfwks.dll"        ' "u2fwks.dll" for 32bit
        FormatType = crUXFLotusWk3Type
    Case 14    ' Excel 2.1
        FormatDLLName = "uxfxls.dll"        ' "u2fxls.dll" for 32bit
        FormatType = crUXFXls2Type
    Case 15    ' Excel 3.0
        FormatDLLName = "uxfxls.dll"        ' "u2fxls.dll" for 32bit
        FormatType = crUXFXls3Type
    Case 16    ' Excel 4.0
        FormatDLLName = "uxfxls.dll"        ' "u2fxls.dll" for 32bit
        FormatType = crUXFXls4Type
    Case 17    ' Excel 5.0
        FormatDLLName = "uxfxls.dll"        ' "u2fxls.dll" for 32bit
        FormatType = crUXFXls5Type
    Case 18    ' ODBC
    Case 19    ' HTML 3.0 Draft Standard
        FormatType = crUXFHTML3Type
    Case 20    ' HTML 3.0 Explorer 2.0
        FormatType = crUXFExplorer2Type
    Case 21    ' HTML 3.0 Netscape 2.0
        FormatType = crUXFNetscape2Type
End Select
' Set export options based on selected export destination
Select Case ExportFormat
    Case 0 To 17
    Select Case ExportDestination
        Case 0        ' Export to File
            Result =    crPEExportToDisk(MainJob, "c:\myfilename" &
vbNullChar,
    FormatDLLName & vbNullChar, FormatType, UseSameNumberFormat,
    UseSameDateFormat, StringDelimiter & vbNullChar, FieldDelimiter &
    vbNullChar)
        Case 1        ' Export to MAPI
            Result =    crPEExportToMapi(MainJob, MAPIToList & vbNullChar,
MAPICCList &
    vbNullChar, MAPISubject & vbNullChar, MAPIMessage & vbNullChar,
    FormatDLLName & vbNullChar, FormatType, UseSameNumberFormat,
    UseSameDateFormat, StringDelimiter & vbNullChar, FieldDelimiter &
    vbNullChar)
        Case 2        ' Export to Exchange
            Result =    crPEExportToExch(MainJob, EXCHProfile & vbNullChar,
EXCHPassword
    & vbNullChar, EXCHFolderPath & vbNullChar, FormatDLLName &
    vbNullChar, FormatType, UseSameNumberFormat, UseSameDateFormat,
    StringDelimiter & vbNullChar, FieldDelimiter & vbNullChar)
    End Select
    Case 18        ' Export to ODBC
        Result =    crPEExportToODBC(MainJob, DataSource & vbNullChar,
UserID &
    vbNullChar, Password & vbNullChar, TableName & vbNullChar)
    Case 19 To 21    ' Export to HTML
        Result =    crPEExportToHTML(MainJob, FormatType, "c:\myfilename" &
    vbNullChar)
End Select
' Start the print job
Result = PEStartPrintJob(MainJob, 1)
' Close the print job
PEClosePrintJob (MainJob)
' Close the engine
PECloseEngine


VB Sample Code for handling errors

Private Sub ErrorTrap(ByVal Source$, ByVal jobnum%)

    Dim result%, errorcode%, textHandle&, TextLength%, ErrorText$

    ' Check for any error codes

    errorcode% = PEGetErrorCode(jobnum%)

    If errorcode% <> 0 Then

        ' If there is an error code, find out what it means

        result% = PEGetErrorText(jobnum%, textHandle&, TextLength%)

        If result% = 0 Then

            ' If getting the text failed, say so

            ErrorText$ = "Error in ErrorTrap routine"

        Else

            ' Get the text from the handle

            ErrorText$ = String$(TextLength%, 0)

            result% = crvbHandleToBstr(textHandle&, ErrorText$,
TextLength%)

            ErrorText$ = Trim$(ErrorText$)

            ErrorText$ = Left$(ErrorText$, Len(ErrorText$) - 1)

        End If

        ' Add source text to error text

        ErrorText$ = Source$ & " caused an error: " & ErrorText$

        ' Display the message with an offer to terminate the program

        If MsgBox(ErrorText$ & Chr$(10) & "Do you want to end the
program?", vbYesNo + vbCritical, "An Error Has Occurred!") = vbYes Then

            End

        End If

    End If

End Sub

ActiveX

Sub ErrorTrap(ByVal Source As String)

    ' Check for any error codes

    If CrystalReport1.LastErrorNumber <> 0 Then

        ' If there is an error code, display the source of the error and
error message with an offer to terminate the program

        If MsgBox(Source & " caused an error: " &
CrystalReport1.LastErrorString & Chr$(10) & "Do you want to end the
program?", vbYesNo + vbCritical, "An Error Has Occurred!") = vbYes Then

            End

        End If

    End If

End Sub


VB Sample Code for modifying database table settings

Private Sub mnuTableTableSettings_Click()

    Dim result%, jobnum%, mainjob%, tableCount%, TableN%,
logOnPropogate%, sessionPropogate%

    Dim TableType As PETableType, LogOnInfo As PELogOnInfo, tableLocation
As PETableLocation, SessionInfo As PESessionInfo

    Dim testtableType As PETableType, testlogOnInfo As PELogOnInfo,
testtableLocation As PETableLocation, testsessionInfo As PESessionInfo

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in TableTableSettings", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in TableTableSettings", mainjob%

    End If

    ' Define the size of the table-related structures

    TableType.StructSize = PE_SIZEOF_TABLE_TYPE

    LogOnInfo.StructSize = PE_SIZEOF_LOGON_INFO

    tableLocation.StructSize = PE_SIZEOF_TABLE_LOCATION

    SessionInfo.StructSize = PE_SIZEOF_SESSION_INFO

    testtableType.StructSize = PE_SIZEOF_TABLE_TYPE

    testlogOnInfo.StructSize = PE_SIZEOF_LOGON_INFO

    testtableLocation.StructSize = PE_SIZEOF_TABLE_LOCATION

    testsessionInfo.StructSize = PE_SIZEOF_SESSION_INFO

    ' Load the Sections form for re-use as a available tables form

    Load Sections

    CenterForm Sample, Sections

    Sections.Caption = "Tables"

    ' Get number of tables used in report

    tableCount% = PEGetNTables(jobnum%)

    ErrorTrap "GetNTables in TableTableSettings", jobnum%

    ' Fill section list on section form with tables

    ' It would be nice to use the names of the tables, but there's no way
to find out what they are

    For TableN% = 0 To tableCount% - 1

        Sections!lstSections.AddItem "Table " & TableN%

    Next TableN%

    ' Start a loop for setting different table settings - exit by
pressing ok on the sections form

    Do While True

        ' Show Section selector form 1 ' Modally

        Sections.Show 1 ' Modal

        ' Find which button was pressed to hide the Sections form

        Select Case Sections.Tag

            Case "Ok"

                Exit Do

            Case "Edit"

                ' Get table number from table list on sections form

                TableN% = Sections!lstSections.ListIndex

                ' Load TableSettings form to fill in table settings data

                Load TableSettings

                CenterForm Sample, TableSettings

                ' Load table type data

                result% = PEGetNthTableType(jobnum%, TableN%, TableType)

                ErrorTrap "GetNthTableType in TableTableSettings", jobnum%

                TableSettings!lblDLLName.Caption = TableType.DLLName

                TableSettings!lblDescriptiveName.Caption =
TableType.DescriptiveName

                Select Case TableType.DBType

                    Case PE_DT_STANDARD

                        TableSettings!lblDBType.Caption = "Standard"

                    Case PE_DT_SQL

                        TableSettings!lblDBType.Caption = "SQL"

                End Select

                ' Load logoninfo data

                result% = PEGetNthTableLogOnInfo(jobnum%, 0,
logOnInfo.ServerName, logOnInfo.DatabaseName, logOnInfo.UserID)

                ErrorTrap "GetNthTableLogOnInfo in TableTableSettings",
jobnum%

                TableSettings!txtServerName.Text = LogOnInfo.ServerName

                TableSettings!txtDatabaseName.Text =
LogOnInfo.DatabaseName

                TableSettings!txtLogOnUserID.Text = LogOnInfo.UserID

                ' Load location data

                result% = PEGetNthTableLocation(jobnum%, TableN%,
tableLocation.Location)

                ErrorTrap "GetNThTableLocation in TableTableSettings",
jobnum%

                TableSettings!txtTableLocation.Text =
tableLocation.Location

                ' Load session info data

                result% = PEGetNthTableSessionInfo(jobnum%, tableN%,
sessionInfo.UserID, sessionInfo.SessionHandle)

                ErrorTrap "GetNthTableSessionInfo in TableTableSettings",
jobnum%

                TableSettings!txtSessionUserID.Text = SessionInfo.UserID

                TableSettings!txtSessionHandle.Text =
SessionInfo.SessionHandle

                ' Another infinite loop

                Do While True

                    ' Display TableSettings form

                    TableSettings.Show 1 ' Modal

                    Select Case TableSettings.Tag

                        Case "Ok"

                            ' Get propagation flags

                            If MsgBox("Propagate changes to log on info
across tables?", vbYesNo + vbQuestion, "Propagate Log On Changes?") =
vbYes Then logOnPropogate% = True Else logOnPropogate% = False

                            If MsgBox("Propagate changes to session info
across tables?", vbYesNo + vbQuestion, "Propagate Session Changes?") =
vbYes Then sessionPropogate% = True Else sessionPropogate% = False

                            ' Set log on info

                            LogOnInfo.ServerName =
TableSettings!txtServerName.Text & Chr$(0)

                            LogOnInfo.DatabaseName =
TableSettings!txtDatabaseName.Text & Chr$(0)

                            LogOnInfo.UserID =
TableSettings!txtLogOnUserID.Text & Chr$(0)

                            LogOnInfo.Password =
TableSettings!txtLogOnPassword.Text & Chr$(0)

                            result% = PESetNthTableLogOnInfo(jobnum%,
tableN%, logOnInfo.ServerName, logOnInfo.DatabaseName, logOnInfo.UserID,
logOnInfo.Password, logOnPropogate%)

                            ErrorTrap "SetNthTableLogOnInfo in
TableTableSettings", jobnum%

                            ' Set table location

                            tableLocation.Location =
TableSettings!txtTableLocation.Text & Chr$(0)

                            result% = PESetNthTableLocation(jobnum%,
TableN%, tableLocation.Location)

                            ErrorTrap "SetNthTableLocation in
TableTableSettings", jobnum%

                            ' Set table session info

                            SessionInfo.UserID =
TableSettings!txtSessionUserID.Text & Chr$(0)

                            SessionInfo.Password =
TableSettings!txtSessionPassword.Text & Chr$(0)

                            SessionInfo.SessionHandle =
Val(TableSettings!txtSessionHandle.Text)

                            result% = PESetNthTableSessionInfo(jobnum%,
tableN%, sessionInfo.UserID, sessionInfo.Password,
SessionInfo.SessionHandle, sessionPropogate%)

                            ErrorTrap "SetNthTableSessionInfo in
TableTableSettings", jobnum%

                            Exit Do

                        Case "Test"

                            ' To test table settings properly, we must set
all the revised settings

                            ' on the table settings form into the print
job, but after testing, must

                            ' also set the settings back to the original
ones - changes are only set

                            ' when the user presses "Ok"

                            ' So with all original settings loaded in the
various structures, a "test"

                            ' set of structures pick up the new settings
from the form and load them

                            ' into the print job.

                            ' Then the table connectivity is tested, the
results reported and the

                            ' table settings restored from the original
set of structures

                            ' Set log on info into temp structures

                            testlogOnInfo.ServerName =
TableSettings!txtServerName.Text & Chr$(0)

                            testlogOnInfo.DatabaseName =
TableSettings!txtDatabaseName.Text & Chr$(0)

                            testlogOnInfo.UserID =
TableSettings!txtLogOnUserID.Text & Chr$(0)

                            testlogOnInfo.Password =
TableSettings!txtLogOnPassword.Text & Chr$(0)

                            result% = PESetNthTableLogOnInfo(jobnum%,
tableN%, testlogOnInfo.ServerName, testlogOnInfo.DatabaseName,
testlogOnInfo.UserID, testlogOnInfo.Password, False)

                            ErrorTrap "SetNthTableLogOnInfo for Test in
TableTableSettings", jobnum%

                            ' Set table location into temp structures

                            testtableLocation.Location =
TableSettings!txtTableLocation.Text & Chr$(0)

                            result% = crPESetNthTableLocation(jobnum%,
TableN%, testtableLocation.Location)

                            ErrorTrap "SetNthTableLocation for Test in
TableTableSettings", jobnum%

                            ' Set table session info into temp structures

                            testsessionInfo.UserID =
TableSettings!txtSessionUserID.Text & Chr$(0)

                            testsessionInfo.Password =
TableSettings!txtSessionPassword.Text & Chr$(0)

                            testsessionInfo.SessionHandle =
Val(TableSettings!txtSessionHandle.Text)

                            result% = PESetNthTableSessionInfo(jobnum%,
tableN%, sessionInfo.UserID, sessionInfo.Password,
SessionInfo.SessionHandle, sessionPropogate%)

                            ErrorTrap "SetNthTableSessionInfo for Test in
TableTableSettings", jobnum%

                            ' Test connectivity

                            result% = PETestNthTableConnectivity(jobnum%,
TableN%)

                            ' If there's an error, result% will equal zero,
ErrorTrap will present the message

                            If result% = 0 Then

                                ErrorTrap "TestNthTableConnectivity in
TableTableSettings", jobnum%

                            Else

                                MsgBox "Table Connectivity tests out fine",
vbOKOnly, "Passed Test"

                            End If

                            ' Restore settings

                            result% = PESetNthTableLogOnInfo(jobnum%,
tableN%, logOnInfo.ServerName, logOnInfo.DatabaseName, logOnInfo.UserID,
logOnInfo.Password, logOnPropogate%)

                            ErrorTrap "SetNthTableLogOnInfo for UnTest in
TableTableSettings", jobnum%

                            result% = PESetNthTableLocation(jobnum%,
TableN%, tableLocation.Location)

                            ErrorTrap "SetNthTableLocation for UnTest in
TableTableSettings", jobnum%

                            result% = PESetNthTableSessionInfo(jobnum%,
tableN%, sessionInfo.UserID, sessionInfo.Password,
SessionInfo.SessionHandle, sessionPropogate%)

                            ErrorTrap "SetNthTableSessionInfo for UnTest
in TableTableSettings", jobnum%

                        Case "Cancel"

                            MsgBox "Cancel was pressed - no changes will
be made to the table settings", vbOKOnly + vbCritical, "Cancel Pressed"

                            Exit Do

                    End Select

                Loop

                Unload TableSettings

        End Select

    Loop

    Unload Sections

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        ' Simplified version of the custom-link preview routine (no
custom buttons)

        result% = PEOutputToWindow(jobnum%, "Table Settings Demonstration
Preview" & Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, 0, 0)

        ErrorTrap "OutputtoWindow in TableTableSettings", jobnum%

        result% = PEStartPrintJob(jobnum%, True)

        ErrorTrap "StartPrintJob in TableTableSettings", jobnum%

        result% = 1

        Do While result% <> 0

            DoEvents

            DoEvents

            result% = PEGetWindowHandle(jobnum%)

        Loop

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in TableTableSettings", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Table Settings Complete!", vbOKOnly, "Operation Succeeded"

End Sub

ActiveX

Private Sub mnuTableTableSettings_Click()

    Dim TempText As String

    Dim hwndPreviewWindow As Long

    CrystalReport1.ReportFileName = lblReportName.Caption ' Name from
label on sample form

    ' Load TableSettings form to fill in table settings data

    Load TableSettings

    CenterForm Sample, TableSettings

    TableSettings.Show 1

    Select Case TableSettings.Tag

        Case "Ok"

            ' Set log on info

            TempText = "DSN = " & TableSettings!txtServerName.Text & ";"

            TempText = TempText & "UID = " &
TableSettings!txtLogOnUserID.Text & ";"

            TempText = TempText & "PWD = " &
TableSettings!txtLogOnPassword.Text & ";"

            TempText = TempText & "DSQ = " &
TableSettings!txtDatabaseName.Text

            CrystalReport1.Connect = TempText

            ' Set table session info

            CrystalReport1.UserName = TableSettings!txtSessionUserID.Text

            CrystalReport1.Password =
TableSettings!txtSessionPassword.Text

            CrystalReport1.SessionHandle =
Val(TableSettings!txtSessionHandle.Text)

        Case "Cancel"

            MsgBox "Cancel was pressed - no changes will be made to the
table settings", vbOKOnly + vbCritical, "Cancel Pressed"

    End Select

    Unload TableSettings

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        CrystalReport1.Destination = 0 ' Window

        CrystalReport1.Action = 1 ' Print

        ErrorTrap "TableSettings"

        hwndPreviewWindow = GetActiveWindow()

        Do While IsWindow(hwndPreviewWindow)

            DoEvents

        Loop

    End If

    ' Close the report

    CrystalReport1.ReportFileName = ""

    MsgBox "Table Settings Complete!", vbOKOnly, "Operation Completed"

End Sub


VB Sample Code for modifying formulas

Private Sub mnuEditFormulas_Click()

    Dim result%, jobnum%, mainjob%, formulacount%, FormulaN%,
NameHandle&, NameLength%, textHandle&, TextLength%

    Dim formulaName$, FormulaText$

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in EditFormulas", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubreport in EditFormulas", mainjob%

    End If

    ' Count how many formulas there are

    formulacount% = PEGetNFormulas(jobnum%)

    If formulacount% = -1 Then

        ' Something went wrong

        ErrorTrap "GetNFormulas in EditFormulas", jobnum%

    ElseIf formulacount% = 0 Then

        ' None!

        MsgBox "There are no formulas in this report.", vbOKOnly +
vbCritical, "No Formulas"

    Else

        ' There are formulas

        ' The formula display form is loaded so that the list box can be
filled with formula names

        Load Formula

        CenterForm Sample, Formula

        ' Loop through the number of formulas determined by
PEGetNFormulas

        For FormulaN% = 0 To formulacount% - 1

            ' Get the handles and lengths for name and text

            result% = PEGetNthFormula(jobnum%, FormulaN%, NameHandle&,
NameLength%, textHandle&, TextLength%)

            ErrorTrap "GetNthFormula in EditFormulas", jobnum%

            ' Set chr$(0) into the strings based on the lengths retrieved
in the preceding call

            ' NOTE! Failure to do this step results in General Protection
Faults

            formulaName$ = String$(NameLength%, 0)

            FormulaText$ = String$(TextLength%, 0)

            ' crvbHandleToBstr fills the strings

            result% = crvbHandleToBstr(NameHandle&, formulaName$,
NameLength%)

            ErrorTrap "HandleToBstr on Name in EditFormulas", jobnum%

            result% = crvbHandleToBstr(textHandle&, FormulaText$,
TextLength%)

            ErrorTrap "HandleToBstr on Text in EditFormulas", jobnum%

            ' The fieldname string is then inserted into the list box on
the sort order form

            Formula!lstNameList.AddItem formulaName$

            Formula!lstTextList.AddItem FormulaText$

        Next FormulaN%

        ' The formula list box and editor are in an infinite loop so that
multiple formulas

        ' can be edited sequentially - pressing Ok or Cancel on the
formula list form exits the loop

        Do While True

            Formula.Show 1 ' Modal

            ' Now that execution has returned, check what button was
pressed and react accordingly

            Select Case Formula.Tag

                Case "Ok"

                    If MsgBox("Do you want to change the formulas of this
print job?", vbYesNo + vbQuestion, "Change Formulas?") = vbYes Then

                        ' Make changes to the print job formulas - note
that this has no permanent affect on the report

                        ' Changes made at the API level cannot be stored
in the report

                        For FormulaN% = 0 To Formula!lstNameList.ListCount
- 1

                            formulaName$ =
Formula!lstNameList.List(FormulaN%) & Chr$(0)

                            FormulaText$ =
Formula!lstTextList.List(FormulaN%) & Chr$(0)

                            ' Set the formula

                            result% = PESetFormula(jobnum%, formulaName$,
FormulaText$)

                            ErrorTrap "SetFormula in EditFormulas", jobnum%

                        Next FormulaN%

                    End If

                    Exit Do

                Case "Edit"

                    ' Although in theory we could use the data in the
formula list boxes, for demonstration

                    ' purposes, let's load the data for the formulas using
the GetFormula call

                    ' Get the name of the formula from the formula list box

                    formulaName$ =
Formula!lstNameList.List(Formula!lstNameList.ListIndex)

                    ' Get the handle and length for the formula text

                    result% = PEGetFormula(jobnum%, formulaName$,
textHandle&, TextLength%)

                    ErrorTrap "GetFormula in EditFormulas", jobnum%

                    ' Get the string of the formula text

                    FormulaText$ = String$(TextLength%, 0)

                    result% = crvbHandleToBstr(textHandle&, FormulaText$,
TextLength%)

                    ErrorTrap "HandleToBstr for Text in EditFormulas",
jobnum%

                    ' Load the formula edit box with data and show it 1 '
Modally

                    Load FormulaEdit

                    CenterForm Sample, FormulaEdit

                    FormulaEdit.Caption = "Editing Formula: " &
formulaName$

                    FormulaEdit!lblOriginalFormula.Caption = FormulaText$

                    FormulaEdit!txtEditFormula.Text = FormulaText$

                    ' The formula edit procedure is placed in an infinite
loop to allow for repeat editing and testing

                    Do While True

                        FormulaEdit.Show 1 ' Modal

                        ' A button has been pressed on the formula edit
form - find out which and act accordingly

                        Select Case FormulaEdit.Tag

                            Case "Ok"

                                ' Replace the formula text in the list box
with the edited formula text

Formula!lstTextList.List(Formula!lstTextList.ListIndex) =
FormulaEdit!txtEditFormula.Text

                                Exit Do

                            Case "Test"

                                ' In order to test the formula, you have
to set it first

                                FormulaText$ =
FormulaEdit!txtEditFormula.Text & Chr$(0)

                                result% = PESetFormula(jobnum%,
formulaName$, FormulaText$)

                                ErrorTrap "SetFormula in EditFormulas",
jobnum%

                                result% = PECheckFormula(jobnum%,
formulaName$)

                                If result% = 0 Then

                                    MsgBox "The formula has an error.",
vbOKOnly + vbCritical, "Error!"

                                Else

                                    MsgBox "The formula has no errors.",
vbOKOnly + vbInformation, "No Error"

                                End If

                                ' Now set the formula back to the original
- the user can choose to keep the changes later

                                FormulaText$ =
FormulaEdit!lblOriginalFormula.Caption & Chr$(0)

                                result% = PESetFormula(jobnum%,
formulaName$, FormulaText$)

                                ErrorTrap "SetFormula in EditFormulas",
jobnum%

                            Case "Cancel"

                                MsgBox "Cancel was pressed on the Formula
edit form. The formula will not be changed.", vbOKOnly + vbInformation,
"Cancel Pressed"

                                Exit Do

                        End Select

                    Loop

                    Unload FormulaEdit

                Case "Cancel"

                    MsgBox "Cancel was pressed on the Formula form. The
formulas of the print job will not be changed.", vbOKOnly +
vbInformation, "Cancel Pressed"

                    Exit Do

            End Select

        Loop

        ' Finished with the sort order form - unload it

        Unload Formula

        ' Offer opportunity to see what you did to the report

        If MsgBox("Do you want to preview the report?", vbYesNo +
vbQuestion, "Preview Report?") = vbYes Then

            ' Simplified version of the custom-link preview routine (no
custom buttons)

            result% = PEOutputToWindow(jobnum%, "Formula Demonstration
Preview" & Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, 0, 0)

            ErrorTrap "OutputtoWindow in EditFormulas", jobnum%

            result% = PEStartPrintJob(jobnum%, True)

            ErrorTrap "StartPrintJob in EditFormulas", jobnum%

            result% = 1

            Do While result% <> 0

                DoEvents

                DoEvents

                result% = PEGetWindowHandle(jobnum%)

            Loop

        End If

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubreport in EditFormulas", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Formula Edit Complete!", vbOKOnly, "Operation Succeeded"

End Sub

ActiveX

Sub mnuEditFormulas_Click()

    Dim formulaN As Integer, GetFormulaN As String

    Dim hwndPreviewWindow As Long

    CrystalReport1.ReportFileName = lblReportName.Caption ' Name from
label on sample form

    ' Set up endless loop (only ends with an Exit Do) for editing
multiple formulas

    Do While True

        GetForumlaN = InputBox("Enter formula number to edit. Press
Cancel to end editing of formulas:", "Enter Formula Number",
Str$(formulaN))

        ' if a zero length string, then Cancel was pressed, exit the loop

        If GetForumlaN = "" Then Exit Do

        ' Otherwise a formula number was entered, display a input box for
the formula

        formulaN = Val(GetForumlaN)

        GetForumlaN = InputBox("Enter formula number " & formulaN & "
using format 'FormulaName= Formula'. Do not put an @ at the front of the
formula. All field names must be in braces. Press Cancel to abort editing
of formula:", "Enter Formula", CrystalReport1.Formulas(formulaN))

        If GetForumlaN = "" Then Exit Do

        CrystalReport1.Formulas(formulaN) = GetForumlaN

        formulaN = formulaN + 1

    Loop

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        CrystalReport1.Destination = 0 ' Window

        CrystalReport1.Action = 1 ' Print

        ErrorTrap "EditFormulas"

        hwndPreviewWindow = GetActiveWindow()

        Do While IsWindow(hwndPreviewWindow)

            DoEvents

        Loop

    End If

    ' Close the report

    CrystalReport1.ReportFileName = ""

    MsgBox "Formula Edit Complete!", vbOKOnly, "Operation Completed"

End Sub


VB Sample Code for modifying graphs

Private Sub mnuFormatGraphs_Click()

    Dim result%, jobnum%, mainjob%, sectionN%, sectionCode%, GraphN%,
GraphType%, TempText$

    Dim GraphDataInfo As PEGraphDataInfo, GraphOptions As PEGraphOptions,
GraphTextInfo As PEGraphTextInfo

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in FormatGraphs", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in FormatGraphs", mainjob%

    End If

    ' Define the size of structures

    GraphDataInfo.StructSize = PE_SIZEOF_GRAPH_DATA_INFO

    GraphOptions.StructSize = PE_SIZEOF_GRAPH_OPTIONS

    GraphTextInfo.StructSize = PE_SIZEOF_GRAPH_TEXT_INFO

    ' Load the Sections form for displaying the selection of sections
available

    Load Sections

    CenterForm Sample, Sections

    Sections.Caption = "Graph Sections"

    ' Fill section list box with appropriate sections for report

    result% = PEGetNSections(jobnum%)

    For sectionN% = 0 To result% - 1

        sectionCode% = PEGetSectionCode(jobnum%, sectionN%)

        Select Case sectionCode%

            Case Is >= 8000

                TempText$ = "Report Footer"

            Case Is >= 7000

                TempText$ = "Page Footer"

            Case Is >= 5000

                TempText$ = "Group Footer"

            Case Is >= 4000

                TempText$ = "Detail"

            Case Is >= 3000

                TempText$ = "Group Header"

            Case Is >= 2000

                TempText$ = "Page Header"

            Case Is >= 1000

                TempText$ = "Report Header"

            Case Else

                TempText$ = "Unknown Section"

        End Select

        Sections!lstSections.AddItem TempText$

        Sections!lstSections.ItemData(Sections!lstSections.NewIndex) =
sectionCode%

    Next sectionN%

    ' Start a loop for setting different section settings - exit by
pressing ok on the sections form

    Do While True

        ' Show Section selector form 1 ' Modally

        Sections.Show 1 ' Modal

        ' Find which button was pressed to hide the Sections form

        Select Case Sections.Tag

            Case "Ok"

                Exit Do

            Case "Edit"

                ' Get the section code from the Section form

                sectionCode% =
Sections!lstSections.ItemData(Sections!lstSections.ListIndex)

                ' Get graph number

                GraphN% = Val(InputBox("Enter graph number, first graph
in section is zero.", "Graph Number", "0"))

                ' Load Graph edit form

                Load Graphs

                CenterForm Sample, Graphs

                ' Get Graph data

                result% = PEGetGraphData(jobnum%, sectionCode%, GraphN%,
GraphDataInfo)

                ErrorTrap "GetGraphData in FormatGraphs", jobnum%

                ' Fill in graph data on form

                Graphs!txtrowGroupN.Text = GraphDataInfo.RowGroupN

                Graphs!txtcolGroupN.Text = GraphDataInfo.ColGroupN

                Graphs!txtsummarizedFieldN.Text =
GraphDataInfo.SummarizedFieldN

                ' Use a loop to find the matching graph direction
description in the combo box

                Graphs!cmbgraphDirection.ListIndex = -1

                Do While Graphs!cmbgraphDirection.ListIndex <>
Graphs!cmbgraphDirection.ListCount - 1

                    Graphs!cmbgraphDirection.ListIndex =
Graphs!cmbgraphDirection.ListIndex + 1

                    If
Graphs!cmbgraphDirection.ItemData(Graphs!cmbgraphDirection.ListIndex) =
GraphDataInfo.GraphDirection Then Exit Do

                Loop

                If
Graphs!cmbgraphDirection.ItemData(Graphs!cmbgraphDirection.ListIndex) <>
GraphDataInfo.GraphDirection Then Graphs!cmbgraphDirection.ListIndex = -
1

                ' Get Graph Options

                result% = crPEGetGraphOptions(jobnum%, sectionCode%,
graphN%, graphOptions.GroupMaxValue, graphOptions.GroupMinValue,
graphOptions.ShowDataValue, graphOptions.ShowGridLine,
graphOptions.VerticalBars, graphOptions.ShowLegend,
graphOptions.FontFaceName)

                ErrorTrap "GetGraphOptions in FormatGraphs", jobnum%

                ' Fill in graph options on form

                Graphs!txtgraphMaxValue.Text = GraphOptions.GraphMaxValue

                Graphs!txtgraphMinValue.Text = GraphOptions.GraphMinValue

                Graphs!chkshowDataValue.Value =
IIf(GraphOptions.ShowDataValue, 1, 0)

                Graphs!chkshowGridLine.Value =
IIf(GraphOptions.ShowGridLine, 1, 0)

                Graphs!chkverticalBars.Value =
IIf(GraphOptions.VerticalBars, 1, 0)

                Graphs!chkshowLegend.Value = IIf(GraphOptions.ShowLegend,
1, 0)

                Graphs!txtfontFaceName.Text = GraphOptions.FontFaceName

                ' Get Graph Text

                result% = PEGetGraphText(jobnum%, sectionCode%, GraphN%,
GraphTextInfo)

                ErrorTrap "GetGraphText in FormatGraphs", jobnum%

                ' Fill in graph texts on form

                Graphs!txtgraphTitle.Text = GraphTextInfo.GraphTitle

                Graphs!txtgraphSubTitle.Text =
GraphTextInfo.GraphSubTitle

                Graphs!txtgraphFootNote.Text =
GraphTextInfo.GraphFootNote

                Graphs!txtgraphGroupsTitle.Text =
GraphTextInfo.GraphGroupsTitle

                Graphs!txtgraphSeriesTitle.Text =
GraphTextInfo.GraphSeriesTitle

                Graphs!txtgraphXAxisTitle.Text =
GraphTextInfo.GraphXAxisTitle

                Graphs!txtgraphYAxisTitle.Text =
GraphTextInfo.GraphYAxisTitle

                Graphs!txtgraphZAxisTitle.Text =
GraphTextInfo.GraphZAxisTitle

                ' Get Graph Type

                result% = PEGetGraphType(jobnum%, sectionCode%, GraphN%,
GraphType%)

                ErrorTrap "GetGraphType in FormatGraphs", jobnum%

                ' Fill in graph type using loop to find combo box match
on form

                Graphs!cmbgraphType.ListIndex = -1

                Do While Graphs!cmbgraphType.ListIndex <>
Graphs!cmbgraphType.ListCount - 1

                    Graphs!cmbgraphType.ListIndex =
Graphs!cmbgraphType.ListIndex + 1

                    If
Graphs!cmbgraphType.ItemData(Graphs!cmbgraphType.ListIndex) = GraphType%
Then Exit Do

                Loop

                If
Graphs!cmbgraphType.ItemData(Graphs!cmbgraphType.ListIndex) <>
GraphType% Then Graphs!cmbgraphType.ListIndex = -1

                ' Display Graph edit form

                Graphs.Show 1 ' Modal

                Select Case Graphs.Tag

                    Case "Ok"

                        ' Set graph data

                        GraphDataInfo.RowGroupN =
Val(Graphs!txtrowGroupN.Text)

                        GraphDataInfo.ColGroupN =
Val(Graphs!txtcolGroupN.Text)

                        GraphDataInfo.SummarizedFieldN =
Val(Graphs!txtsummarizedFieldN.Text)

                        GraphDataInfo.GraphDirection =
Graphs!cmbgraphDirection.ItemData(Graphs!cmbgraphDirection.ListIndex)

                        result% = PESetGraphData(jobnum%, sectionCode%,
GraphN%, GraphDataInfo)

                        ErrorTrap "SetGraphData in FormatGraphs", jobnum%

                        ' Set graph options

                        GraphOptions.GraphMaxValue =
Val(Graphs!txtgraphMaxValue.Text)

                        GraphOptions.GraphMinValue =
Val(Graphs!txtgraphMinValue.Text)

                        GraphOptions.ShowDataValue =
IIf(Graphs!chkshowDataValue.Value = 1, True, False)

                        GraphOptions.ShowGridLine =
IIf(Graphs!chkshowGridLine.Value = 1, True, False)

                        GraphOptions.VerticalBars =
IIf(Graphs!chkverticalBars.Value = 1, True, False)

                        GraphOptions.ShowLegend =
IIf(Graphs!chkshowLegend.Value = 1, True, False)

                        GraphOptions.FontFaceName =
Graphs!txtfontFaceName.Text

                        result% = crPESetGraphOptions(jobnum%,
sectionCode%, graphN%, graphOptions.GraphMaxValue,
graphOptions.GraphMinValue, graphOptions.ShowDataValue,
graphOptions.ShowGridLine, graphOptions.VerticalBars,
graphOptions.ShowLegend, graphOptions.FontFaceName)

                        ErrorTrap "SetGraphOptions in FormatGraphs",
jobnum%

                        ' Set graph text

                        GraphTextInfo.GraphTitle =
Graphs!txtgraphTitle.Text & Chr$(0)

                        GraphTextInfo.GraphSubTitle =
Graphs!txtgraphSubTitle.Text & Chr$(0)

                        GraphTextInfo.GraphFootNote =
Graphs!txtgraphFootNote.Text & Chr$(0)

                        GraphTextInfo.GraphGroupsTitle =
Graphs!txtgraphGroupsTitle.Text & Chr$(0)

                        GraphTextInfo.GraphSeriesTitle =
Graphs!txtgraphSeriesTitle.Text & Chr$(0)

                        GraphTextInfo.GraphXAxisTitle =
Graphs!txtgraphXAxisTitle.Text & Chr$(0)

                        GraphTextInfo.GraphYAxisTitle =
Graphs!txtgraphYAxisTitle.Text & Chr$(0)

                        GraphTextInfo.GraphZAxisTitle =
Graphs!txtgraphZAxisTitle.Text & Chr$(0)

                        result% = PESetGraphText(jobnum%, sectionCode%,
GraphN%, GraphTextInfo)

                        ErrorTrap "SetGraphText in FormatGraphs", jobnum%

                        ' Set graph type

                        GraphType% =
Graphs!cmbgraphType.ItemData(Graphs!cmbgraphType.ListIndex)

                        result% = PESetGraphType(jobnum%, sectionCode%,
GraphN%, GraphType%)

                        ErrorTrap "SetGraphType in FormatGraphs", jobnum%

                    Case "Cancel"

                        MsgBox "Cancel was pressed - no changes will be
made to the graph settings", vbOKOnly + vbCritical, "Cancel Pressed"

                        Exit Do

                End Select

                Unload Graphs

        End Select

    Loop

    Unload Sections

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        ' Simplified version of the custom-link preview routine (no
custom buttons)

        result% = PEOutputToWindow(jobnum%, "Graph Preview" & Chr$(0),
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0)

        ErrorTrap "OutputtoWindow in FormatGraphs", jobnum%

        result% = PEStartPrintJob(jobnum%, True)

        ErrorTrap "StartPrintJob in FormatGraphs", jobnum%

        result% = 1

        Do While result% <> 0

            DoEvents

            DoEvents

            result% = PEGetWindowHandle(jobnum%)

        Loop

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in FormatGraphs", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Graphs Complete!", vbOKOnly, "Operation Succeeded"

End Sub

ActiveX

Private Sub mnuFormatGraphs_Click()

    Dim GraphN As Integer, graphDataN As Integer, graphOptionsN As
Integer

    Dim graphTextN As Integer, graphTypeN As Integer, TempText As String

    Dim hwndPreviewWindow As Long

    CrystalReport1.ReportFileName = lblReportName.Caption ' Name from
label on sample form

    ' Load the Sections form for displaying the selection of sections
available

    Load Sections

    CenterForm Sample, Sections

    Sections.Caption = "Graph Sections"

    ' Start a loop for setting different section settings - exit by
pressing ok on the sections form

    Do While True

        ' Show Section selector form modally

        Sections.Show 1

        ' Find which button was pressed to hide the Sections form

        Select Case Sections.Tag

            Case "Ok"

                Exit Do

            Case "Edit"

                ' Get graph number

                GraphN = Val(InputBox("Enter graph number, first graph in
section is zero.", "Graph Number", "0"))

                ' Load Graph edit form

                Load Graphs

                CenterForm Sample, Graphs

                ' Display Graph edit form

                Graphs.Show 1

                Select Case Graphs.Tag

                    Case "Ok"

                        ' Graph data

                        If Val(Graphs!txtrowGroupN.Text) <> 0 Then

                            ' Create section name and graph number

                            TempText = Sections!cmbSectionType.Text & "."
& Sections!txtGroup.Text & "." & Sections!txtSectionNumber.Text & ";" &
Trim(Str$(GraphN))

                            ' Set graph data

                            TempText = TempText & ";Group" &
Graphs!txtrowGroupN.Text

                            TempText = TempText & ";Group" &
Graphs!txtcolGroupN.Text

                            TempText = TempText & ";" &
Graphs!txtsummarizedFieldN.Text

                            TempText = TempText & ";" &
Graphs!cmbgraphDirection.List(Graphs!cmbgraphDirection.ListIndex)

                            CrystalReport1.GraphData(graphDataN) = TempText

                            graphDataN = graphDataN + 1

                        End If

                        ' Set graph options

                        If Len(Trim(Graphs!txtfontFaceName.Text)) <> 0
Then

                            TempText = Sections!cmbSectionType.Text & "."
& Sections!txtGroup.Text & "." & Sections!txtSectionNumber.Text & ";" &
Trim(Str$(GraphN))

                            TempText = TempText & ";" &
Graphs!txtfontFaceName.Text

                            If Graphs!chkverticalBars.Value = 1 Then
TempText = TempText & ";V" Else TempText = TempText & ";H"

                            If Graphs!chkshowDataValue.Value = 1 Then
TempText = TempText & ";T" Else TempText = TempText & ";F"

                            If Graphs!chkshowGridLine.Value = 1 Then
TempText = TempText & ";T" Else TempText = TempText & ";F"

                            If Graphs!chkshowLegend.Value = 1 Then TempText
= TempText & ";T" Else TempText = TempText & ";F"

                            TempText = TempText & ";" &
Graphs!txtgraphMaxValue.Text

                            TempText = TempText & ";" &
Graphs!txtgraphMinValue.Text

                            CrystalReport1.GraphOptions(graphOptionsN) =
TempText

                            graphOptionsN = graphOptionsN + 1

                        End If

                        ' Set graph text

                        If Len(Trim(Graphs!txtgraphTitle.Text)) <> 0 Then

                            TempText = Sections!cmbSectionType.Text & "."
& Sections!txtGroup.Text & "." & Sections!txtSectionNumber.Text & ";" &
Trim(Str$(GraphN))

                            TempText = TempText & ";" &
Graphs!txtgraphTitle.Text

                            TempText = TempText & ";" &
Graphs!txtgraphSubTitle.Text

                            TempText = TempText & ";" &
Graphs!txtgraphFootNote.Text

                            TempText = TempText & ";" &
Graphs!txtgraphGroupsTitle.Text

                            TempText = TempText & ";" &
Graphs!txtgraphSeriesTitle.Text

                            TempText = TempText & ";" &
Graphs!txtgraphXAxisTitle.Text

                            TempText = TempText & ";" &
Graphs!txtgraphYAxisTitle.Text

                            TempText = TempText & ";" &
Graphs!txtgraphZAxisTitle.Text

                            CrystalReport1.GraphText(graphTextN) = TempText

                            graphTextN = graphTextN + 1

                        End If

                        ' Set graph type

                        If Len(Trim(Graphs!cmbgraphType.Text)) <> 0 Then

                            TempText = Sections!cmbSectionType.Text & "."
& Sections!txtGroup.Text & "." & Sections!txtSectionNumber.Text & ";" &
Trim(Str$(GraphN))

                            TempText = TempText & ";" &
Graphs!cmbgraphType.Text

                            CrystalReport1.GraphType(graphTypeN) = TempText

                            graphTypeN = graphTypeN + 1

                        End If

                    Case "Cancel"

                        MsgBox "Cancel was pressed - no changes will be
made to the graph settings", vbOKOnly + vbCritical, "Cancel Pressed"

                        Exit Do

                End Select

                Unload Graphs

        End Select

    Loop

    Unload Sections

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        CrystalReport1.Destination = 0 ' Window

        CrystalReport1.Action = 1 ' Print

        ErrorTrap "FormatGraphs"

        hwndPreviewWindow = GetActiveWindow()

        Do While IsWindow(hwndPreviewWindow)

            DoEvents

        Loop

    End If

    ' Close the report

    CrystalReport1.ReportFileName = ""

    MsgBox "Graphs Complete!", vbOKOnly, "Operation Completed"

End Sub


VB Sample Code for modifying group conditions

Private Sub mnuEditGroupConditions_Click()

    Dim result%, jobnum%, mainjob%, groupcount%, groupN%, fieldHandle&,
fieldLength%, Condition%, Direction%

    Dim FieldName$, TempText$

    If Not CRYSTAL_PRO Then

        MsgBox "Modifying Group Conditions is a Crystal Pro only
feature.", vbOKOnly + vbCritical, "Crystal Pro Only"

        Exit Sub

    End If

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in EditGroupCondition", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in EditGroupCondition", mainjob%

    End If

    ' Count how many groups there are

    groupcount% = PEGetNGroups(jobnum%)

    If groupcount% = -1 Then

        ' Something went wrong

        ErrorTrap "GetNGroups in EditGroupCondition", jobnum%

    ElseIf groupcount% = 0 Then

        ' None!

        MsgBox "There are no groups defined in this report.", vbOKOnly +
vbCritical, "No Groups"

    Else

        ' There are groups

        ' The Group Conditions form is loaded to display the various
conditions

        Load GroupConditions

        CenterForm Sample, GroupConditions

        ' Loop through the number of sort fields determined by
PEGetNSortFields

        For groupN% = 0 To groupcount% - 1

            ' Get the fieldhandle, length and sort direction

            result% = PEGetGroupCondition(jobnum%, groupN%, fieldHandle&,
fieldLength%, Condition%, Direction%)

            ErrorTrap "GetGroupCondition in EditGroupCondition", jobnum%

            ' Set chr$(0) into the fieldname string based on the length
retrieved in the preceding call

            ' NOTE! Failure to do this step results in GPFs

            FieldName$ = String$(fieldLength%, 0)

            ' crvbHandleToBstr fills the fieldname string with the name
of the sort field

            result% = crvbHandleToBstr(fieldHandle&, FieldName$,
fieldLength%)

            ErrorTrap "HandleToBstr for FieldName in EditGroupCondition",
jobnum%

            ' The fieldname string is then inserted into the list box on
the sort order form

            GroupConditions!lstFieldName.AddItem FieldName$

            ' To determine what condition text should be displayed in the
list box, a select case statement

            ' using a mask determines what type of condition type, then
the condition itself

            Select Case Condition% And PE_GC_TYPEMASK

                Case PE_GC_TYPEOTHER

                    ' Others have no conditions

                    TempText$ = ""

                Case PE_GC_TYPEDATE

                    Select Case Condition% And PE_GC_CONDITIONMASK

                        Case PE_GC_DAILY

                            TempText$ = "Daily"

                        Case PE_GC_WEEKLY

                            TempText$ = "Weekly"

                        Case PE_GC_BIWEEKLY

                            TempText$ = "BiWeekly"

                        Case PE_GC_SEMIMONTHLY

                            TempText$ = "SemiMonthly"

                        Case PE_GC_MONTHLY

                            TempText$ = "Monthly"

                        Case PE_GC_QUARTERLY

                            TempText$ = "Quarterly"

                        Case PE_GC_SEMIANNUALLY

                            TempText$ = "SemiAnnually"

                        Case PE_GC_ANNUALLY

                            TempText$ = "Annually"

                    End Select

                Case PE_GC_TYPEBOOLEAN

                    Select Case Condition% And PE_GC_CONDITIONMASK

                        Case PE_GC_TOYES

                            TempText$ = "To Yes"

                        Case PE_GC_TONO

                            TempText$ = "To No"

                        Case PE_GC_EVERYYES

                            TempText$ = "Every Yes"

                        Case PE_GC_EVERYNO

                            TempText$ = "Every No"

                        Case PE_GC_NEXTISYES

                            TempText$ = "Next Is Yes"

                        Case PE_GC_NEXTISNO

                            TempText$ = "Next Is No"

                    End Select

            End Select

            GroupConditions!lstCondition.AddItem TempText$

            ' Store the condition value in the item data in the list box

GroupConditions!lstCondition.ItemData(GroupConditions!lstFieldName.NewIn
dex) = Condition%

            ' Load direction into the direction list box

            If Direction% = PE_SF_DESCENDING Then

                TempText$ = "Des"

            Else

                TempText$ = "Asc"

            End If

            GroupConditions!lstDirection.AddItem TempText$

        Next groupN%

        ' Once the list is complete, the sort order form is shown 1 '
Modally - execution in this module will stop

        ' until the sort order form is hidden (by pressing Ok or Cancel)

        GroupConditions.Show 1 ' Modal

        ' Now that execution has returned, check what button was pressed
and react accordingly

        Select Case GroupConditions.Tag

            Case "Ok"

                If MsgBox("Do you want to change the group conditions of
this print job?", vbYesNo + vbQuestion, "Change Group Conditions?") =
vbYes Then

                    ' Make changes to the print job group conditions -
note that this has no permanent affect on the report

                    ' Changes made at the API level cannot be stored in
the report

                    For groupN% = 0 To
GroupConditions!lstFieldName.ListCount - 1

                        ' Copy the name of the sort field from the list box

                        FieldName$ =
GroupConditions!lstFieldName.List(groupN%) & Chr$(0)

                        Condition% =
GroupConditions!lstCondition.ItemData(groupN%)

                        If GroupConditions!lstDirection.List(groupN%) =
"Des" Then

                            Direction% = PE_SF_DESCENDING

                        Else

                            Direction% = PE_SF_ASCENDING

                        End If

                        result% = PESetGroupCondition(jobnum%, groupN%,
FieldName$, Condition%, Direction%)

                        ErrorTrap "GetGroupCondition in
EditGroupCondition", jobnum%

                    Next groupN%

                End If

            Case "Cancel"

                MsgBox "Cancel was pressed on the Group Conditions form.
The group condition of the print job will not be changed.", vbOKOnly +
vbInformation, "Cancel Pressed"

        End Select

        ' Finished with the sort order form - unload it

        Unload GroupConditions

        ' Offer opportunity to see what you did to the report

        If MsgBox("Do you want to preview the report?", vbYesNo +
vbQuestion, "Preview Report?") = vbYes Then

            ' Simplified version of the custom-link preview routine (no
custom buttons)

            result% = PEOutputToWindow(jobnum%, "Sort Order Demonstration
Preview" & Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, 0, 0)

            ErrorTrap "OutputtoWindow in EditGroupCondition", jobnum%

            result% = PEStartPrintJob(jobnum%, True)

            ErrorTrap "StartPrintJob in EditGroupCondition", jobnum%

            result% = 1

            Do While result% <> 0

                DoEvents

                DoEvents

                result% = PEGetWindowHandle(jobnum%)

            Loop

        End If

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in EditGroupCondition", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Group Conditions Complete!", vbOKOnly, "Operation Succeeded"

End Sub

ActiveX

Private Sub mnuEditGroupConditions_Click()

    Dim groupN As Integer

    Dim GroupName As String, FieldName As String, Condition As String,
SortDirection As String

    Dim hwndPreviewWindow As Long

    If Not CRYSTAL_PRO Then

        MsgBox "Modifying Group Conditions is a Crystal Pro only
feature.", vbOKOnly + vbCritical, "Crystal Pro Only"

        Exit Sub

    End If

    CrystalReport1.ReportFileName = lblReportName.Caption ' Name from
label on sample form

    ' Set up endless loop (only ends with an Exit Do) for editing
multiple group conditions

    Do While True

        GroupName = InputBox("Enter group condition to edit. Press Cancel
to end editing of group conditions:", "Enter Group Condition Number",
Str$(groupN))

        ' if a zero length string, then Cancel was pressed, exit the loop

        If GroupName = "" Then Exit Do

        ' Otherwise a group condition number was entered, convert it

        groupN = Val(GroupName)

        ' Groupname must be preceded by the word group

        GroupName = "GROUP" & GroupName

        ' Get FieldName

        FieldName = InputBox("Enter field name for group condition. Press
Cancel to end editing of group conditions. Field names must be encased in
braces:", "Enter Field Name:", "{}")

        ' if a zero length string, then Cancel was pressed, exit the loop

        If FieldName = "" Then Exit Do

        ' Get Condition

        Condition = InputBox("Enter condition code for grouping. If field
is a date or boolean field, please refer to the help file for conditions,
for all other fields, leave set to default (ANYCHANGE):", "Enter
Condition", "ANYCHANGE")

        If Condition = "" Then Exit Do

        ' Get Sort Direction

        SortDirection = InputBox("Enter the sort direction. Press Cancel
to end editing of group conditions. Press 'A' for Ascending, 'D' for
Descending.", "Enter Sort Direction", "A")

        If SortDirection = "" Then Exit Do

        ' Load Group Condition with data input

        CrystalReport1.GroupCondition(groupN) = GroupName & FieldName &
Condition & SortDirection

        groupN = groupN + 1

    Loop

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        CrystalReport1.Destination = 0 ' Window

        CrystalReport1.Action = 1 ' Print

        ErrorTrap "GroupConditions"

        hwndPreviewWindow = GetActiveWindow()

        Do While IsWindow(hwndPreviewWindow)

            DoEvents

        Loop

    End If

    ' Close the report

    CrystalReport1.ReportFileName = ""

    MsgBox "Group Conditions Complete!", vbOKOnly, "Operation Completed"

End Sub


VB Sample Code for modifying parameter fields

Private Sub mnuEditParameterFields_Click()

    Dim result%, jobnum%, mainjob%, paramCount%, paramN%

    Dim ParameterFieldInfo As PEParameterFieldInfo

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in EditParameterFields", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in EditParameterFields", mainjob%

    End If

    ' Define the size of the structures

    ParameterFieldInfo.StructSize = PE_SIZEOF_VARINFO_TYPE

    ' Get number of parameters

    paramCount% = PEGetNParameterFields(jobnum%)

    ErrorTrap "GetNParameterFields in EditParameterFields", jobnum%

    If paramCount% < 1 Then

        MsgBox "There are no field parameters in this report. Execution
must halt.", vbOKOnly + vbCritical, "No Field Parameters"

    Else

        ' If there are parameters, load them into the sections form

        Load Sections

        CenterForm Sample, Sections

        Sections.Tag = "Field Parameter List"

        For paramN% = 0 To paramCount% - 1

            ' Get parameter

            result% = crPEGetNthParameterField(job, 0,
ParameterFieldInfo.ValueType, ParameterFieldInfo.DefaultValueSet,
ParameterFieldInfo.CurrentValueSet, ParameterFieldInfo.Name,
ParameterFieldInfo.Prompt, ParameterFieldInfo.DefaultValue,
ParameterFieldInfo.CurrentValue)

            ErrorTrap "GetNthParameterField in EditParameterFields",
jobnum%

            ' Put parameter into sections form

            Sections!lstSections.AddItem ParameterFieldInfo.Name

        Next paramN%

        ' Set up infinite loop to allow for modifying multiple parameters

        Do While True

            ' Show form 1 ' Modally

            Sections.Show 1 ' Modal

            Select Case Sections.Tag

                Case "Ok"

                    ' Finished making changes, unload the parameter form
and exit the loop

                    Unload Parameters

                    Exit Do

                Case "Edit"

                    ' Edit selected parameter

                    ' Load parameter info into structure

                    result% = crPEGetNthParameterField(job, 0,
ParameterFieldInfo.ValueType, ParameterFieldInfo.DefaultValueSet,
ParameterFieldInfo.CurrentValueSet, ParameterFieldInfo.Name,
ParameterFieldInfo.Prompt, ParameterFieldInfo.DefaultValue,
ParameterFieldInfo.CurrentValue)

                    ErrorTrap "GetNthParameterField in
EditParameterFields", jobnum%

                    ' Load parameter form and fill it with the info from
the structure

                    Load Parameters

                    CenterForm Sample, Parameters

                    Parameters!txtName.Text = ParameterFieldInfo.Name

                    Parameters!txtPrompt.Text = ParameterFieldInfo.Prompt

                    Parameters!cmbValueType.ListIndex =
ParameterFieldInfo.ValueType

                    Parameters!txtDefaultValue.Text =
ParameterFieldInfo.DefaultValue

                    Parameters!txtCurrentValue.Text =
ParameterFieldInfo.CurrentValue

                    ' Show parameter form 1 ' Modally

                    Parameters.Show 1 ' Modal

                    Select Case Parameters.Tag

                        Case "Ok"

                            ' Save changes

                            ParameterFieldInfo.Name =
Parameters!txtName.Text

                            ParameterFieldInfo.Prompt =
Parameters!txtPrompt.Text

                            ParameterFieldInfo.ValueType =
Parameters!cmbValueType.ListIndex

                            ParameterFieldInfo.DefaultValue =
Parameters!txtDefaultValue.Text & Chr$(0)

                            ParameterFieldInfo.CurrentValue =
Parameters!txtCurrentValue.Text & Chr$(0)

                            ParameterFieldInfo.DefaultValueSet =
IIf(Parameters!chkDefaultValueSet.Value, True, False)

                            ParameterFieldInfo.CurrentValueSet =
IIf(Parameters!chkCurrentValueSet.Value, True, False)

                            result% = crPESetNthParameterField(jobnum%,
Sections!lstSections.ListIndex, ParameterFieldInfo.ValueType,
ParameterFieldInfo.DefaultValueSet, ParameterFieldInfo.CurrentValueSet,
ParameterFieldInfo.Name, ParameterFieldInfo.Prompt,
ParameterFieldInfo.DefaultValue, ParameterFieldInfo.CurrentValue)

                            ErrorTrap "SetNthParameterField in
EditParameterFields", jobnum%

                        Case "Cancel"

                            ' Changes aren't saved

                    End Select

            End Select

        Loop

        Unload Sections

    End If

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        ' Simplified version of the custom-link preview routine (no
custom buttons)

        result% = PEOutputToWindow(jobnum%, "Field Parameters
Demonstration Preview" & Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT, 0, 0)

        ErrorTrap "OutputtoWindow in EditParameterFields", jobnum%

        result% = PEStartPrintJob(jobnum%, True)

        ErrorTrap "StartPrintJob in EditParameterFields", jobnum%

        result% = 1

        Do While result% <> 0

            DoEvents

            DoEvents

            result% = PEGetWindowHandle(jobnum%)

        Loop

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in EditParameterFields", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Field Parameters Complete!", vbOKOnly, "Operation Succeeded"

End Sub

ActiveX

Private Sub mnuEditParameterFields_Click()

    Dim ParamN As Integer, ParamName As String, ParamData As String

    Dim hwndPreviewWindow As Long

    CrystalReport1.ReportFileName = lblReportName.Caption ' Name from
label on sample form

    ' Set up endless loop (only ends with an Exit Do) for editing
multiple parameters

    Do While True

        ParamName = InputBox("Enter parameter number to edit. Press
Cancel to end editing of parameters:", "Enter Parameter Number",
Str$(ParamN))

        ' if a zero length string, then Cancel was pressed, exit the loop

        If ParamName = "" Then Exit Do

        ' Otherwise a parameter number was entered, covert and collect
data

        ParamN = Val(ParamName)

        ParamName = InputBox("Enter name of parameter to edit. Press
Cancel to end editing of parameters:", "Enter Parameter Name", "")

        If ParamName = "" Then Exit Do

        ParamData = InputBox("Enter new value for parameter. Press Cancel
to end editing of parameters:", "Enter Parameter Value", "")

        If ParamData = "" Then Exit Do

        CrystalReport1.ParameterFields(ParamN) = ParamName & ";" &
ParamData

        ParamN = ParamN + 1

    Loop

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        CrystalReport1.Destination = 0 ' Window

        CrystalReport1.Action = 1 ' Print

        ErrorTrap "ParameterFields"

        hwndPreviewWindow = GetActiveWindow()

        Do While IsWindow(hwndPreviewWindow)

            DoEvents

        Loop

    End If

    ' Close the report

    CrystalReport1.ReportFileName = ""

    MsgBox "Field Parameters Complete!", vbOKOnly, "Operation Completed"

End Sub


VB Sample Code for modifying section format formulas

Private Sub mnuEditSectionFormat_Click()

    Dim result%, jobnum%, mainjob%, sectionN%, sectionCode%, formulaName%

    Dim TempText$

    If Not CRYSTAL_PRO Then

        MsgBox "Options are a Crystal Pro only feature.", vbOKOnly +
vbCritical, "Crystal Pro Only"

        Exit Sub

    End If

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in EditSectionFormat", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in EditSectionFormat", mainjob%

    End If

    ' Load the Sections form for displaying the selection of sections
available

    Load Sections

    CenterForm Sample, Sections

    ' Start a loop for editing different section format formulae - exit
by pressing ok on the sections form

    Do While True

        Sections.Caption = "Select Section"

        Sections!lstSections.Clear

        ' Fill section list box with appropriate sections for report

        result% = PEGetNSections(jobnum%)

        ErrorTrap "GetNSections in EditSectionFormat", jobnum%

        For sectionN% = 0 To result% - 1

            sectionCode% = PEGetSectionCode(jobnum%, sectionN%)

            ErrorTrap "GetSectionCode in EditSectionFormat", jobnum%

            Select Case sectionCode%

                Case Is >= 8000

                    TempText$ = "Report Footer"

                Case Is >= 7000

                    TempText$ = "Page Footer"

                Case Is >= 5000

                    TempText$ = "Group Footer"

                Case Is >= 4000

                    TempText$ = "Detail"

                Case Is >= 3000

                    TempText$ = "Group Header"

                Case Is >= 2000

                    TempText$ = "Page Header"

                Case Is >= 1000

                    TempText$ = "Report Header"

                Case Else

                    TempText$ = "Unknown Section"

            End Select

            Sections!lstSections.AddItem TempText$

            Sections!lstSections.ItemData(Sections!lstSections.NewIndex)
= sectionCode%

        Next sectionN%

        ' Show Section selector form 1 ' Modally

        Sections.Show 1 ' Modal

        ' Find which button was pressed to hide the Sections form

        Select Case Sections.Tag

            Case "Ok"

                Exit Do

            Case "Edit"

                ' Get the section code from the Section form

                sectionCode% =
Sections!lstSections.ItemData(Sections!lstSections.ListIndex)

                ' Reload the Sections form with the formula name constants

                Sections.Caption = "Select Section Format Formula"

                Sections!lstSections.Clear

                Sections!lstSections.AddItem "Section Visibility"

Sections!lstSections.ItemData(Sections!lstSections.NewIndex) =
SECTION_VISIBILITY

                Sections!lstSections.AddItem "New Page Before"

Sections!lstSections.ItemData(Sections!lstSections.NewIndex) =
NEW_PAGE_BEFORE

                Sections!lstSections.AddItem "Keep Section Together"

Sections!lstSections.ItemData(Sections!lstSections.NewIndex) =
KEEP_SECTION_TOGETHER

                Sections!lstSections.AddItem "Suppress Blank Section"

Sections!lstSections.ItemData(Sections!lstSections.NewIndex) =
SUPPRESS_BLANK_SECTION

                Sections!lstSections.AddItem "Reset Page Num After"

Sections!lstSections.ItemData(Sections!lstSections.NewIndex) =
RESET_PAGE_N_AFTER

                Sections!lstSections.AddItem "Print at Bottom of Page"

Sections!lstSections.ItemData(Sections!lstSections.NewIndex) =
PRINT_AT_BOTTOM_OF_PAGE

                Sections!lstSections.AddItem "Underlay Section"

Sections!lstSections.ItemData(Sections!lstSections.NewIndex) =
UNDERLAY_SECTION

                Sections!lstSections.AddItem "Section Back Colour"

Sections!lstSections.ItemData(Sections!lstSections.NewIndex) =
SECTION_BACK_COLOUR

                ' Set up infinite loop to allow for multiple format
formula edits

                Do While True

                    ' Display Section form (now showing format formulas)

                    Sections.Show 1 ' Modal

                    Select Case Sections.Tag

                        Case "Ok"

                            Exit Do

                        Case "Edit"

                            ' Get formula name code from Sections list box

                            formulaName% =
Sections!lstSections.ItemData(Sections!lstSections.ListIndex)

                            ' Get new section format formula

                            TempText$ = InputBox$("Enter new section format
formula:", "New Formula", "")

                            If TempText$ = "" Then

                                MsgBox "Cancel pressed or no formula
entered. No changes will be made to this format formula.", vbOKOnly +
vbCritical, "Cancel Pressed"

                            Else

                                result% =
PESetSectionFormatFormula(jobnum%, sectionCode%, formulaName%,
TempText$)

                                ErrorTrap "SetSectionFormatFormula in
EditSectionFormat", jobnum%

                            End If

                    End Select

                Loop

        End Select

    Loop

    Unload Sections

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        ' Simplified version of the custom-link preview routine (no
custom buttons)

        result% = PEOutputToWindow(jobnum%, "Lines/Section Demonstration
Preview" & Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, 0, 0)

        ErrorTrap "OutputtoWindow in EditSectionFormat", jobnum%

        result% = PEStartPrintJob(jobnum%, True)

        ErrorTrap "StartPrintJob in EditSectionFormat", jobnum%

        result% = 1

        Do While result% <> 0

            DoEvents

            DoEvents

            result% = PEGetWindowHandle(jobnum%)

        Loop

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in EditSectionFormat", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Section Format Formula Complete!", vbOKOnly, "Operation
Succeeded"

End Sub


VB Sample Code for modifying sections and lines

Private Sub mnuFormatLinesSections_Click()

    Dim result%, jobnum%, mainjob%, sectionN%, sectionCode%,
MinimumHeight%, nDetailCopies%, lineN%, LineHeight%, LineAscent%

    Dim TempText$

    Dim SectionOptions As PESectionOptions

    If Not CRYSTAL_PRO Then

        MsgBox "Options are a Crystal Pro only feature.", vbOKOnly +
vbCritical, "Crystal Pro Only"

        Exit Sub

    End If

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in FormatLinesSections", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in FormatLinesSections", mainjob%

    End If

    ' Define the size of the SectionOptions structure

    SectionOptions.StructSize = PE_SIZEOF_SECTION_OPTIONS

    ' Load the Sections form for displaying the selection of sections
available

    Load Sections

    CenterForm Sample, Sections

    Sections.Caption = "Edit Sections"

    ' Fill section list box with appropriate sections for report

    result% = PEGetNSections(jobnum%)

    ErrorTrap "GetNSections in FormatLinesSections", jobnum%

    For sectionN% = 0 To result% - 1

        sectionCode% = PEGetSectionCode(jobnum%, sectionN%)

        ErrorTrap "GetSectionCode in FormatLinesSections", jobnum%

        Select Case sectionCode%

            Case Is >= 8000

                TempText$ = "Report Footer"

            Case Is >= 7000

                TempText$ = "Page Footer"

            Case Is >= 5000

                TempText$ = "Group Footer"

            Case Is >= 4000

                TempText$ = "Detail"

            Case Is >= 3000

                TempText$ = "Group Header"

            Case Is >= 2000

                TempText$ = "Page Header"

            Case Is >= 1000

                TempText$ = "Report Header"

            Case Else

                TempText$ = "Unknown Section"

        End Select

        Sections!lstSections.AddItem TempText$

        Sections!lstSections.ItemData(Sections!lstSections.NewIndex) =
sectionCode%

    Next sectionN%

    ' Start a loop for setting different section settings - exit by
pressing Ok on the sections form

    Do While True

        ' Show Section selector form 1 ' Modally

        Sections.Show 1 ' Modal

        ' Find which button was pressed to hide the Sections form

        Select Case Sections.Tag

            Case "Ok"

                Exit Do

            Case "Edit"

                ' Get the section code from the Section form

                sectionCode% =
Sections!lstSections.ItemData(Sections!lstSections.ListIndex)

                ' Load Section edit form

                Load SectionEdit

                CenterForm Sample, SectionEdit

                ' Get Section format data

                result% = PEGetSectionFormat(jobnum%, sectionCode%,
SectionOptions)

                ErrorTrap "GetSectionFormat in FormatLinesSections",
jobnum%

                ' Fill in section format data on form

                SectionEdit!chkVisible.Value =
IIf(SectionOptions.Visible, 1, 0)

                SectionEdit!chkNewPageBefore.Value =
IIf(SectionOptions.NewPageBefore, 1, 0)

                SectionEdit!chkNewPageAfter.Value =
IIf(SectionOptions.NewPageAfter, 1, 0)

                SectionEdit!chkKeepTogether.Value =
IIf(SectionOptions.KeepTogether, 1, 0)

                SectionEdit!chkSuppressBlankLines.Value =
IIf(SectionOptions.SuppressBlankSection, 1, 0)

                SectionEdit!chkResetPageNAfter.Value =
IIf(SectionOptions.ResetPageNAfter, 1, 0)

                SectionEdit!chkprintAtBottomOfPage.Value =
IIf(SectionOptions.PrintAtBottomOfPage, 1, 0)

                ' Get minimum section height

                result% = PEGetMinimumSectionHeight(jobnum%,
sectionCode%, MinimumHeight%)

                ErrorTrap "GetMinimumSectionHeight in
FormatLinesSections", jobnum%

                ' Fill in minimum section height

                SectionEdit!txtMinHeight.Text = MinimumHeight%

                ' Get number of times each detail section is printed

                result% = PEGetNDetailCopies(jobnum%, nDetailCopies%)

                ErrorTrap "GetNDetailCopies in FormatLinesSections",
jobnum%

                ' Fill in number of times detail section is printed

                SectionEdit!txtNDetailCopies.Text = nDetailCopies%

                ' Another infinite loop

                Do While True

                    ' Display SectionEdit form

                    SectionEdit.Show 1 ' Modal

                    Select Case SectionEdit.Tag

                        Case "Ok"

                            ' Get section format data from form

                            If SectionEdit!chkVisible.Value = 1 Then
SectionOptions.Visible = True Else SectionOptions.Visible = False

                            If SectionEdit!chkNewPageBefore.Value = 1 Then
SectionOptions.NewPageBefore = True Else SectionOptions.NewPageBefore =
False

                            If SectionEdit!chkNewPageAfter.Value = 1 Then
SectionOptions.NewPageAfter = True Else SectionOptions.NewPageAfter =
False

                            If SectionEdit!chkKeepTogether.Value = 1 Then
SectionOptions.KeepTogether = True Else SectionOptions.KeepTogether =
False

                            If SectionEdit!chkSuppressBlankLines.Value =
1 Then SectionOptions.SuppressBlankSection = True Else
SectionOptions.SuppressBlankSection = False

                            If SectionEdit!chkResetPageNAfter.Value = 1
Then SectionOptions.ResetPageNAfter = True Else
SectionOptions.ResetPageNAfter = False

                            If SectionEdit!chkprintAtBottomOfPage.Value =
1 Then SectionOptions.PrintAtBottomOfPage = True Else
SectionOptions.PrintAtBottomOfPage = False

                            ' Set into report

                            result% = PESetSectionFormat(jobnum%,
sectionCode%, SectionOptions)

                            ErrorTrap "SetSectionFormat in
FormatLinesSections", jobnum%

                            ' Get minimum section height from form

                            MinimumHeight% =
Val(SectionEdit!txtMinHeight.Text)

                            result% = PESetMinimumSectionHeight(jobnum%,
sectionCode%, MinimumHeight%)

                            ErrorTrap "SetMinimumSectionHeight in
FormatLinesSections", jobnum%

                            ' If a font name has been entered, change the
font of the section

                            If Len(Trim(SectionEdit!txtFontName.Text)) <>
0 Then

                                result% = PESetFont(jobnum%, sectionCode%,
IIf(SectionEdit!chkFields.Value = 1, PE_FIELDS, 0) Or
IIf(SectionEdit!chkText.Value = 1, PE_TEXT, 0),
SectionEdit!txtFontName.Text, FF_DONTCARE, DEFAULT_PITCH, ANSI_CHARSET,
Val(SectionEdit!txtFontSize.Text), IIf(SectionEdit!chkItalics.Value = 1,
True, False), IIf(SectionEdit!chkUnderline.Value = 1, True, False),
IIf(SectionEdit!chkStrikethru.Value = 1, True, False),
IIf(SectionEdit!chkBold.Value = 1, FW_BOLD, FW_NORMAL))

                                ErrorTrap "SetFont in FormatLinesSections",
jobnum%

                            End If

                            ' Get number of times each detail section is
printed

                            nDetailCopies% =
Val(SectionEdit!txtNDetailCopies.Text)

                            result% = PESetNDetailCopies(jobnum%,
nDetailCopies%)

                            ErrorTrap "SetNDetailCopies in
FormatLinesSections", jobnum%

                            Exit Do

                        Case "Cancel"

                            MsgBox "Cancel was pressed - no changes will
be made to the section settings", vbOKOnly + vbCritical, "Cancel Pressed"

                            Exit Do

                    End Select

                Loop

                Unload SectionEdit

        End Select

    Loop

    Unload Sections

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        ' Simplified version of the custom-link preview routine (no
custom buttons)

        result% = PEOutputToWindow(jobnum%, "Lines/Section Demonstration
Preview" & Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, 0, 0)

        ErrorTrap "OutputtoWindow in FormatLinesSections", jobnum%

        result% = PEStartPrintJob(jobnum%, True)

        ErrorTrap "StartPrintJob in FormatLinesSections", jobnum%

        result% = 1

        Do While result% <> 0

            DoEvents

            DoEvents

            result% = PEGetWindowHandle(jobnum%)

        Loop

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in FormatLinesSections", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Lines/Sections Complete!", vbOKOnly, "Operation Succeeded"

End Sub

ActiveX

Private Sub mnuFormatLinesSections_Click()

    Dim sectionFormatN As Integer, sectionMinHeightN As Integer

    Dim sectionLineHeightN As Integer, sectionFontN As Integer

    Dim TempText As String

    Dim hwndPreviewWindow As Long

    If Not CRYSTAL_PRO Then

        MsgBox "Options are a Crystal Pro only feature.", vbOKOnly +
vbCritical, "Crystal Pro Only"

        Exit Sub

    End If

    CrystalReport1.ReportFileName = lblReportName.Caption ' Name from
label on sample form

    ' Load the Sections form for displaying the selection of sections
available

    Load Sections

    CenterForm Sample, Sections

    Sections.Caption = "Edit Sections"

    ' Start a loop for setting different section settings - exit by
pressing Ok on the sections form

    Do While True

        ' Show Section selector form modally

        Sections.Show 1

        ' Find which button was pressed to hide the Sections form

        Select Case Sections.Tag

            Case "Ok"

                Exit Do

            Case "Edit"

                ' Load Section edit form

                Load SectionEdit

                CenterForm Sample, SectionEdit

                ' Another infinite loop

                Do While True

                    ' Display SectionEdit form

                    SectionEdit.Show 1

                    Select Case SectionEdit.Tag

                        Case "Ok"

                            ' Do section format

                            ' Build section name

                            TempText = Sections!cmbSectionType.Text & "."
& Sections!txtGroup.Text & "." & Sections!txtSectionNumber.Text

                            ' Get section format data from form

                            If SectionEdit!chkVisible.Value = 1 Then
TempText = TempText & ";T" Else TempText = TempText & ";F"

                            If SectionEdit!chkNewPageBefore.Value = 1 Then
TempText = TempText & ";T" Else TempText = TempText & ";F"

                            If SectionEdit!chkNewPageAfter.Value = 1 Then
TempText = TempText & ";T" Else TempText = TempText & ";F"

                            If SectionEdit!chkKeepTogether.Value = 1 Then
TempText = TempText & ";T" Else TempText = TempText & ";F"

                            If SectionEdit!chkSuppressBlankLines.Value =
1 Then TempText = TempText & ";T" Else TempText = TempText & ";F"

                            If SectionEdit!chkResetPageNAfter.Value = 1
Then TempText = TempText & ";T" Else TempText = TempText & ";F"

                            If SectionEdit!chkprintAtBottomOfPage.Value =
1 Then TempText = TempText & ";T" Else TempText = TempText & ";F"

                            ' Load into report and increment counter

                            CrystalReport1.SectionFormat(sectionFormatN)
= TempText

                            sectionFormatN = sectionFormatN + 1

                            ' Get minimum section height from form

                            If Val(SectionEdit!txtMinHeight.Text) <> 0 Then

                                TempText = Sections!cmbSectionType.Text &
"." & Sections!txtGroup.Text & "." & Sections!txtSectionNumber.Text

                                TempText = TempText & ";" &
SectionEdit!txtMinHeight.Text

CrystalReport1.SectionMinHeight(sectionMinHeightN) = TempText

                                sectionMinHeightN = sectionMinHeightN + 1

                            End If

                            ' Get line changes for section from form

                            If Val(SectionEdit!txtLineNum.Text) <> 0 Then

                                TempText = Sections!cmbSectionType.Text &
"." & Sections!txtGroup.Text & "." & Sections!txtSectionNumber.Text

                                TempText = TempText & ";" &
SectionEdit!txtLineNum.Text & ";" & SectionEdit!txtHeight.Text & ";" &
SectionEdit!txtAscent.Text

CrystalReport1.SectionLineHeight(sectionLineHeightN) = TempText

                                sectionLineHeightN = sectionLineHeightN + 1

                            End If

                            ' Get font changes for section from form

                            If Len(Trim(SectionEdit!txtFontName.Text)) <>
0 And Val(SectionEdit!txtFontSize.Text) <> 0 Then

                                TempText = SectionEdit!cmbSectionType.Text
& "." & SectionEdit!txtGroup.Text & "." &
SectionEdit!txtSectionNumber.Text

                                TempText = TempText & ";" &
SectionEdit!txtFontName.Text & ";" & SectionEdit!txtFontSize.Text

                                If SectionEdit!chkItalic.Value = 1 Then
TempText = TempText & ";T" Else TempText = TempText & ";F"

                                If SectionEdit!chkBold.Value = 1 Then
TempText = TempText & ";T" Else TempText = TempText & ";F"

                                If SectionEdit!chkUnderline.Value = 1 Then
TempText = TempText & ";T" Else TempText = TempText & ";F"

                                If SectionEdit!chkStrikethru.Value = 1
Then TempText = TempText & ";T" Else TempText = TempText & ";F"

                                CrystalReport1.SectionFont(sectionFontN)
= TempText

                                sectionFontN = sectionFontN + 1

                            End If

                            Exit Do

                        Case "Cancel"

                            MsgBox "Cancel was pressed - no changes will
be made to the section settings", vbOKOnly + vbCritical, "Cancel Pressed"

                            Exit Do

                    End Select

                Loop

                Unload SectionEdit

        End Select

    Loop

    Unload Sections

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        CrystalReport1.Destination = 0 ' Window

        CrystalReport1.Action = 1 ' Print

        ErrorTrap "FormatLinesSections"

        hwndPreviewWindow = GetActiveWindow()

        Do While IsWindow(hwndPreviewWindow)

            DoEvents

        Loop

    End If

    ' Close the report

    CrystalReport1.ReportFileName = ""

    MsgBox "Lines/Sections Complete!", vbOKOnly, "Operation Completed"

End Sub


VB Sample Code for modifying selection formulas and group selection formulas

Selection formulas

Private Sub mnuEditRecordSelection_Click()

    Dim result%, jobnum%, mainjob%, textHandle&, TextLength%

    Dim SelectionText$

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in EditRecordSelection", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in EditRecordSelection", mainjob%

    End If

    ' Get Record Selection formula handle and length

    result% = PEGetSelectionFormula(jobnum%, textHandle&, TextLength%)

    ErrorTrap "GetSelectionFormula in EditRecordSelection", jobnum%

    ' Get the string of the formula text

    SelectionText$ = String$(TextLength%, 0)

    result% = crvbHandleToBstr(textHandle&, SelectionText$, TextLength%)

    ErrorTrap "HandleToBstr for SelectionText in EditRecordSelection",
jobnum%

    ' Load the formula edit box with data and show it 1 ' Modally

    Load FormulaEdit

    CenterForm Sample, FormulaEdit

    FormulaEdit.Caption = "Editing Record Selection Formula"

    FormulaEdit!lblOriginalFormula.Caption = SelectionText$

    FormulaEdit!txtEditFormula.Text = SelectionText$

    ' The formula edit procedure is placed in an infinite loop to allow
for repeat editing and testing

    Do While True

        FormulaEdit.Show 1 ' Modal

        ' A button has been pressed on the formula edit form - find out
which and act accordingly

        Select Case FormulaEdit.Tag

            Case "Ok"

                ' Replace the selection formula text in the print job with
the edited formula text

                SelectionText$ = FormulaEdit!txtEditFormula.Text & Chr$(0)

                result% = PESetSelectionFormula(jobnum%, SelectionText$)

                ErrorTrap "SetSelectionFormula in EditRecordSelection",
jobnum%

                Exit Do

            Case "Test"

                ' In order to test the formula, you have to set it first

                SelectionText$ = FormulaEdit!txtEditFormula.Text & Chr$(0)

                result% = PESetSelectionFormula(jobnum%, SelectionText$)

                ErrorTrap "SetSelectionFormula for Test in
EditRecordSelection", jobnum%

                result% = PECheckSelectionFormula(jobnum%)

                If result% = 0 Then

                    MsgBox "The formula has an error.", vbOKOnly +
vbCritical, "Error!"

                Else

                    MsgBox "The formula has no errors.", vbOKOnly +
vbInformation, "No Error"

                End If

                ' Now set the formula back to the original - the user can
choose to keep the changes by pressing Ok

                SelectionText$ = FormulaEdit!lblOriginalFormula.Caption &
Chr$(0)

                result% = PESetSelectionFormula(jobnum%, SelectionText$)

                ErrorTrap "SetSelectionFormula for Untest in
EditRecordSelection", jobnum%

            Case "Cancel"

                MsgBox "Cancel was pressed on the Formula edit form. The
formula will not be changed.", vbOKOnly + vbInformation, "Cancel
Pressed"

                Exit Do

        End Select

    Loop

    ' Finished with the formula editting form - unload it

    Unload FormulaEdit

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        ' Simplified version of the custom-link preview routine (no
custom buttons)

        result% = PEOutputToWindow(jobnum%, "Formula Demonstration
Preview" & Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, 0, 0)

        ErrorTrap "OutputtoWindow in EditRecordSelection", jobnum%

        result% = PEStartPrintJob(jobnum%, True)

        ErrorTrap "StartPrintJob in EditRecordSelection", jobnum%

        result% = 1

        Do While result% <> 0

            DoEvents

            DoEvents

            result% = PEGetWindowHandle(jobnum%)

        Loop

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in EditRecordSelection", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Record Selection Formula Edit Complete!", vbOKOnly,
"Operation Succeeded"

End Sub

Group selection formulas

Private Sub mnuEditGroupSelection_Click()

    Dim result%, jobnum%, mainjob%, textHandle&, TextLength%

    Dim SelectionText$

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in EditGroupSelection", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in EditGroupSelection", mainjob%

    End If

    ' Get Group Selection formula handle and length

    result% = PEGetGroupSelectionFormula(jobnum%, textHandle&,
TextLength%)

    ErrorTrap "GetGroupSelectionFormula in GroupSelection", jobnum%

    ' Get the string of the formula text

    SelectionText$ = String$(TextLength%, 0)

    result% = crvbHandleToBstr(textHandle&, SelectionText$, TextLength%)

    ErrorTrap "HandleToBstr for Group SelectionText in GroupSelection",
jobnum%

    ' Load the formula edit box with data and show it 1 ' Modally

    Load FormulaEdit

    CenterForm Sample, FormulaEdit

    FormulaEdit.Caption = "Editing Group Selection Formula"

    FormulaEdit!lblOriginalFormula.Caption = SelectionText$

    FormulaEdit!txtEditFormula.Text = SelectionText$

    ' The formula edit procedure is placed in an infinite loop to allow
for repeat editing and testing

    Do While True

        FormulaEdit.Show 1 ' Modal

        ' A button has been pressed on the formula edit form - find out
which and act accordingly

        Select Case FormulaEdit.Tag

            Case "Ok"

                ' Replace the selection formula text in the print job with
the edited formula text

                SelectionText$ = FormulaEdit!txtEditFormula.Text & Chr$(0)

                result% = PESetGroupSelectionFormula(jobnum%,
SelectionText$)

                ErrorTrap "SetGroupSelectionFormula in GroupSelection",
jobnum%

                Exit Do

            Case "Test"

                ' In order to test the formula, you have to set it first

                SelectionText$ = FormulaEdit!txtEditFormula.Text & Chr$(0)

                result% = PESetGroupSelectionFormula(jobnum%,
SelectionText$)

                ErrorTrap "SetGroupSelectionFormula for Test in
GroupSelection", jobnum%

                result% = PECheckGroupSelectionFormula(jobnum%)

                If result% = 0 Then

                    MsgBox "The formula has an error.", vbOKOnly +
vbCritical, "Error!"

                Else

                    MsgBox "The formula has no errors.", vbOKOnly +
vbInformation, "No Errors"

                End If

                ' Now set the formula back to the original - the user can
choose to keep the changes by pressing Ok

                SelectionText$ = FormulaEdit!lblOriginalFormula.Caption &
Chr$(0)

                result% = PESetGroupSelectionFormula(jobnum%,
SelectionText$)

                ErrorTrap "SetGroupSelectionFormula for Untest in
GroupSelection", jobnum%

            Case "Cancel"

                MsgBox "Cancel was pressed on the Formula edit form. The
formula will not be changed.", vbOKOnly + vbInformation, "Cancel
Pressed"

                Exit Do

        End Select

    Loop

    ' Finished with the formula editing form - unload it

    Unload FormulaEdit

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        ' Simplified version of the custom-link preview routine (no
custom buttons)

        result% = PEOutputToWindow(jobnum%, "Formula Demonstration
Preview" & Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, 0, 0)

        ErrorTrap "OutputtoWindow in GroupSelection", jobnum%

        result% = PEStartPrintJob(jobnum%, True)

        ErrorTrap "StartPrintJob in GroupSelection", jobnum%

        result% = 1

        Do While result% <> 0

            DoEvents

            DoEvents

            result% = PEGetWindowHandle(jobnum%)

        Loop

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in GroupSelection", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Group Selection Formula Edit Complete!", vbOKOnly, "Operation
Succeeded"

End Sub

ActiveX

Selection formulas and group selection formulas

Private Sub mnuEditSelectionFormulas_Click()

    Dim SelForm As String

    Dim hwndPreviewWindow As Long

    CrystalReport1.ReportFileName = lblReportName.Caption ' Name from
label on sample form

    ' Find out what kind of selection formula to work with - record or
group

    Select Case MsgBox("Do you want to edit the record selection formula
or group selection formula? Press Yes to edit the record selection
formula, No to edit the group selection formula, or Cancel:",
vbYesNoCancel + vbQuestion, "Which formula to edit?")

        Case vbYes

            ' Get new record selection formula

            SelForm = InputBox("Enter additional record selection
formula. Press Cancel to abort editing the record selection formula.
Field names must be in braces:", "Enter Record Selection Formula",
CrystalReport1.SelectionFormula)

            ' If a zero length string, cancel was pressed - if not, enter
new formula

            If SelForm <> "" Then

                CrystalReport1.SelectionFormula = SelForm

            End If

        Case vbNo

            ' Get new group selection formula

            SelForm = InputBox("Enter additional group selection formula.
Press Cancel to abort editing the group selection formula. Field names
must be in braces:", "Enter Group Selection Formula",
CrystalReport1.GroupSelectionFormula)

            ' If a zero length string, cancel was pressed - if not, enter
new formula

            If SelForm <> "" Then

                CrystalReport1.GroupSelectionFormula = SelForm

            End If

        Case vbCancel

            MsgBox "Cancel pressed - no selection formula will be
edited.", vbOKOnly + vbCritical, "Cancel Pressed"

    End Select

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        CrystalReport1.Destination = 0 ' Window

        CrystalReport1.Action = 1 ' Print

        ErrorTrap "SelectionFormulas"

        hwndPreviewWindow = GetActiveWindow()

        Do While IsWindow(hwndPreviewWindow)

            DoEvents

        Loop

    End If

    ' Close the report

    CrystalReport1.ReportFileName = ""

    MsgBox "Selection Formula Edit Complete!", vbOKOnly, "Operation
Completed"

End Sub


VB Sample Code for modifying SQL statements

Private Sub mnuTableSQLQuery_Click()

    Dim result%, jobnum%, mainjob%, textHandle&, TextLength%

    Dim SQLText$

    Dim TableType As PETableType, LogOnInfo As PELogOnInfo

    If Not CRYSTAL_PRO Then

        MsgBox "Options are a Crystal Pro only feature.", vbOKOnly +
vbCritical, "Crystal Pro Only"

        Exit Sub

    End If

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in TableSQLQuery", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "PEOpenSubReport in TableSQLQuery", mainjob%

    End If

    ' SQL Queries only exist when the table type is SQL - standard table
types don't have the queries

    ' Note that access databases can be connected as a standard type or
as an SQL type through ODBC

    ' This example is not designed to handle multiple data sources on a
single report - it presumes

    ' that all tables are standard or SQL, and if SQL, from one database

    ' Define the size of the structures

    TableType.StructSize = PE_SIZEOF_TABLE_TYPE

    LogOnInfo.StructSize = PE_SIZEOF_LOGON_INFO

    result% = PEGetNthTableType(jobnum%, 0, TableType)

    ErrorTrap "PEGetNthTableType in TableSQLQuery", jobnum%

    If TableType.DBType = PE_DT_STANDARD Then

        MsgBox "SQL Queries are only available for SQL databases. This
report is attached to a standard database. Select a different report.",
vbOKOnly + vbCritical, "SQL Databases Only!"

    Else

        ' Now that it is confirmed that this is an SQL database, we will
attempt to get logon information

        ' from the crPEGetNthTableLogOnInfo call - this data will be
offered as default for the Logon Server

        ' parameters

        result% = crPEGetNthTableLogOnInfo(jobnum%, 0,
logOnInfo.ServerName, logOnInfo.DatabaseName, logOnInfo.UserID)

        ErrorTrap "GetNthTabelLogOnInfo in TableSQLQuery", jobnum%

        ' Get the fields needed for the LogOn Server call from the user,
defaulting with the data

        ' from the TableLogOnInfo call

        LogOnInfo.ServerName = InputBox$("Enter the name of the Server:",
"Server Name", LogOnInfo.ServerName) & Chr$(0)

        LogOnInfo.DatabaseName = InputBox$("Enter the name of the
Database:", "Database Name", LogOnInfo.DatabaseName) & Chr$(0)

        LogOnInfo.UserID = InputBox("Enter the User ID:", "User ID",
LogOnInfo.UserID) & Chr$(0)

        LogOnInfo.Password = InputBox("Enter the Password:", "Password",
LogOnInfo.Password) & Chr$(0)

        ' Attempt to log on server using parameters

        result% = crPELogOnServer(tableType.DLLName,
logOnInfo.ServerName, logOnInfo.DatabaseName, logOnInfo.UserID,
logOnInfo.Password)

        ErrorTrap "LogOnServer in TableSQLQuery", jobnum%

        ' Get query

        result% = PEGetSQLQuery(jobnum%, textHandle&, TextLength%)

        ErrorTrap "GetSQLQuery in TableSQLQuery", result%

        ' Set chr$(0) into the fieldname string based on the length
retrieved in the preceding call

        ' NOTE! Failure to do this step results in General Protection
Faults

        SQLText$ = String$(TextLength%, 0)

        ' crvbHandleToBstr fills the fieldname string with SQL Query text

        result% = crvbHandleToBstr(textHandle&, SQLText$, TextLength%)

        ErrorTrap "HandleToBstr for SQLText in TableSQLQuery", jobnum%

        ' Re-use formula editor form for showing and editing the SQL
Query for the report

        Load FormulaEdit

        CenterForm Sample, FormulaEdit

        FormulaEdit.Caption = "SQL Query Editor"

        FormulaEdit!cmdTest.Visible = False

        ' Load query text into original and edit boxes

        FormulaEdit!lblOriginalFormula.Caption = SQLText$

        FormulaEdit!txtEditFormula.Text = SQLText$

        ' Show form 1 ' Modally

        FormulaEdit.Show 1 ' Modal

        Select Case FormulaEdit.Tag

            Case "Ok"

                If MsgBox("Set changes to SQL Query into print job?",
vbYesNo + vbQuestion, "Change SQL Query?") = vbYes Then

                    ' Set SQL query changes into print job

                    SQLText$ = FormulaEdit!txtEditFormula.Text & Chr$(0)

                    result% = PESetSQLQuery(jobnum%, SQLText$)

                    ErrorTrap "SetSQLQuery in TableSQLQuery", jobnum%

                End If

            Case "Cancel"

                MsgBox "Cancel was Pressed - no changes will be made to
the SQL Query for this report.", vbOKOnly + vbCritical, "Cancel Pressed"

        End Select

        Unload FormulaEdit

        ' Log off Server

        result% = crPELogOffServer(tableType.DLLName,
logOnInfo.ServerName, logOnInfo.DatabaseName, logOnInfo.UserID,
logOnInfo.Password)

        ErrorTrap "LogOffServer in TableSQLQuery", jobnum%

    End If

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        ' Simplified version of the custom-link preview routine (no
custom buttons)

        result% = PEOutputToWindow(jobnum%, "SQL Query Demonstration
Preview" & Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, 0, 0)

        ErrorTrap "OutputtoWindow in TableSQLQuery", jobnum%

        result% = PEStartPrintJob(jobnum%, True)

        ErrorTrap "StartPrintJob in TableSQLQuery", jobnum%

        result% = 1

        Do While result% <> 0

            DoEvents

            DoEvents

            result% = PEGetWindowHandle(jobnum%)

        Loop

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in TableSQLQuery", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "SQL Query Complete!", vbOKOnly, "Operation Succeeded"

End Sub

ActiveX

Private Sub mnuTableSQLQuery_Click()

    Dim SQLQuery As String

    Dim hwndPreviewWindow As Long

    If Not CRYSTAL_PRO Then

        MsgBox "Options are a Crystal Pro only feature.", vbOKOnly +
vbCritical, "Crystal Pro Only"

        Exit Sub

    End If

    CrystalReport1.ReportFileName = lblReportName.Caption ' Name from
label on sample form

    ' Get SQL Query from user

    SQLQuery = InputBox("Enter SQL Query for report. Press Cancel to
abort editing of SQL Query:", "Enter SQL Query",
CrystalReport1.SQLQuery)

    If SQLQuery <> "" Then

        ' If there is text, load it into the SQLQuery property

        CrystalReport1.SQLQuery = SQLQuery

    End If

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        CrystalReport1.Destination = 0 ' Window

        CrystalReport1.Action = 1 ' Print

        ErrorTrap "TableSQLQuery"

        hwndPreviewWindow = GetActiveWindow()

        Do While IsWindow(hwndPreviewWindow)

            DoEvents

        Loop

    End If

    ' Close the report

    CrystalReport1.ReportFileName = ""

    MsgBox "SQL Query Complete!", vbOKOnly, "Operation Completed"

End Sub


VB Sample Code for modifying Subreports

Private Sub mnuFileSubReportOpen_Click()

    Dim result%, jobnum%, sectionN%, sectionCode%, subreportN%,
subreportHandle&

    Dim x As Integer, y As Integer

    Dim subreportInfo As PESubreportInfo

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in FileSubReportOpen", jobnum%

    ' Define the size of the SubReportInfo structure

    subreportInfo.StructSize = PE_SIZEOF_SUBREPORT_INFO

    ' Load the Sections form for displaying the selection of subreports
available

    Load Sections

    CenterForm Sample, Sections

    Sections.Caption = "Open Subreport"

    Sections!cmdEdit.Caption = "&Cancel"

    ' Find number of sections and loop through each section checking for
the existence of subreports

    sectionN% = PEGetNSections(jobnum%)

    ErrorTrap "GetNSections in FileSubReportOpen", jobnum%

    For x = 0 To sectionN% - 1

        ' Get section code

        sectionCode% = PEGetSectionCode(jobnum%, x)

        ErrorTrap "GetSectionCode in FileSubReportOpen", jobnum%

        ' Get number of subreports in section

        subreportN% = PEGetNSubreportsInSection(jobnum%, sectionCode%)

        ErrorTrap "GetNSubreportsInSection in FileSubReportOpen", jobnum%

        ' If there are subreports, get the handle and name for adding to
list

        If result% > 0 Then

            For y = 0 To subreportN% - 1

                ' Get handle for subreport

                subreportHandle& = PEGetNthSubreportInSection(jobnum%,
sectionCode%, y)

                ErrorTrap "GetNthSubreportInSection in
FileSubReportOpen", jobnum%

                ' Get info for subreport

                result% = PEGetSubreportInfo(jobnum%, subreportHandle&,
subreportInfo)

                ErrorTrap "GetSubReportInfo in FileSubReportOpen", jobnum%

                ' Load info into section form list box

                Sections!lstSections.AddItem subreportInfo.Name

            Next y

        End If

    Next x

    ' If the list box on the sections form is still empty, there are no
subreports in the report

    If Sections!lstSections.ListCount = 0 Then

        MsgBox "There are no subreports in this report. Execution must
halt.", vbOKOnly + vbCritical, "No subreports!"

    Else

        ' Otherwise, show the Sections form 1 ' Modally to allow
selection of a subreport

        Sections.Show 1 ' Modal

        Select Case Sections.Tag

            Case "Ok"

                ' When a subreport is selected, the main sample form shows
the subreport name below the report name

                lblSubreportName.Caption =
Sections!lstSections.List(Sections!lstSections.ListIndex)

                lblSubreportName.Visible = True

                lblSubReportLabel.Visible = True

                picReportHeader.Height = 855

            Case "Edit"

                ' The edit button caption was changed to Cancel for this
case - pressing it cancels selection of a subreport

                MsgBox "Cancel pressed. No subreport will be opened.",
vbOKOnly + vbCritical, "Cancel pressed"

        End Select

    End If

    Unload Sections

    ' Close print job and engine

    PEClosePrintJob jobnum%

    PECloseEngine

End Sub
Related topics:

Working with subreports


VB Sample Code for modifying title, options, margins, and date

Private Sub mnuFormatOptions_Click()

    Dim result%, jobnum%, mainjob%, TitleHandle&, TitleLength%, RepYear%,
RepMonth%, RepDay%

    Dim RepLeft%, RepRight%, RepTop%, RepBottom%

    Dim ReportTitle$, TempText$

    Dim PrintOptions As PEPrintOptions

    If Not CRYSTAL_PRO Then

        MsgBox "Options are a Crystal Pro only feature.", vbOKOnly +
vbCritical, "Crystal Pro Only"

        Exit Sub

    End If

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in FormatOptions", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in FormatOptions", mainjob%

    End If

    ' Load the Options form for filling in the option details of the
report

    Load Options

    CenterForm Sample, Options

    ' Get the report title

    result% = PEGetReportTitle(jobnum%, TitleHandle&, TitleLength%)

    ErrorTrap "GetReportTitle in FormatOptions", jobnum%

    ' Preload the ReportTitle with enough space for the title

    ReportTitle$ = String$(TitleLength%, 0)

    ' Get the title string itself

    result% = crvbHandleToBstr(TitleHandle&, ReportTitle$, TitleLength%)

    ErrorTrap "HandleToBstr for ReportTitle in FormatOptions", jobnum%

    ' Load the title onto the form

    Options!txtTitle.Text = ReportTitle$

    ' Get the print date for the report

    result% = PEGetPrintDate(jobnum%, RepYear%, RepMonth%, RepDay%)

    ErrorTrap "GetPrintDate in FormatOptions", jobnum%

    Options!txtDate.Text = Trim$(Str$(RepMonth%)) & "/" &
Trim$(Str$(RepDay%)) & "/" & Trim$(Str$(RepYear%))

    ' Get print options

    PrintOptions.StructSize = PE_SIZEOF_PRINT_OPTIONS

    result% = PEGetPrintOptions(jobnum%, PrintOptions)

    ErrorTrap "GetPrintOptions in FormatOptions", jobnum%

    ' If page range is set 1 and -1, set options page to All

    If PrintOptions.StartPageN = 1 And PrintOptions.stopPageN = -1 Then

        Options!txtPageFrom.Enabled = False

        Options!txtPageTo.Enabled = False

        Options!chkPageAll.Value = 1 ' Checked

    Else

        Options!txtPageFrom.Enabled = True

        Options!txtPageTo.Enabled = True

        Options!chkPageAll.Value = 0 ' Unchecked

        Options!txtPageFrom.Text = PrintOptions.StartPageN

        Options!txtPageTo.Text = PrintOptions.stopPageN

    End If

    Options!txtCopies.Text = PrintOptions.nReportCopies

    ' Set collation combo box

    Select Case PrintOptions.collation

        Case PE_UNCOLLATED

            Options!cmbCollation.ListIndex = 1

        Case PE_COLLATED

            Options!cmbCollation.ListIndex = 2

        Case PE_DEFAULTCOLLATION

            Options!cmbCollation.ListIndex = 0

    End Select

    ' Get Margins

    result% = PEGetMargins(jobnum%, RepLeft%, RepRight%, RepTop%,
RepBottom%)

    ErrorTrap "GetMargins in FormatOptions", jobnum%

    Options!txtLeft.Text = RepLeft%

    Options!txtRight.Text = RepRight%

    Options!txtTop.Text = RepTop%

    Options!txtBottom.Text = RepBottom%

    ' Show the options form 1 ' Modally

    Options.Show 1 ' Modal

    ' Check what button was pressed

    Select Case Options.Tag

        Case "Ok"

            If MsgBox("Do you wish to modify the report options of this
print job?", vbYesNo + vbQuestion, "Change Report Options?") = vbYes Then

                ' Set the new report title

                ReportTitle$ = Trim$(Options!txtTitle.Text) & Chr$(0)

                result% = PESetReportTitle(jobnum%, ReportTitle$)

                ErrorTrap "SetReportTitle in FormatOptions", jobnum%

                ' Set print date

                RepYear% = Year(DateValue(Options!txtDate.Text))

                RepMonth% = Month(DateValue(Options!txtDate.Text))

                RepDay% = Day(DateValue(Options!txtDate.Text))

                result% = PESetPrintDate(jobnum%, RepYear%, RepMonth%,
RepDay%)

                ErrorTrap "SetPrintDate in FormatOptions", jobnum%

                ' Set print options

                If Options!chkPageAll.Value = 1 Then

                    PrintOptions.StartPageN = 1

                    PrintOptions.stopPageN = -1

                Else

                    PrintOptions.StartPageN =
Val(Options!txtPageFrom.Text)

                    PrintOptions.stopPageN = Val(Options!txtPageTo.Text)

                End If

                PrintOptions.nReportCopies = Val(Options!txtCopies.Text)

                Select Case Options!cmbCollation.Text

                    Case "Collated"

                        PrintOptions.collation = PE_COLLATED

                    Case "Uncollated"

                        PrintOptions.collation = PE_UNCOLLATED

                    Case "Default"

                        PrintOptions.collation = PE_DEFAULTCOLLATION

                End Select

                result% = PESetPrintOptions(jobnum%, PrintOptions)

                ErrorTrap "SetPrintOptions in FormatOptions", jobnum%

                ' Set Margins

                RepLeft% = Val(Options!txtLeft.Text)

                RepRight% = Val(Options!txtRight.Text)

                RepTop% = Val(Options!txtTop.Text)

                RepBottom% = Val(Options!txtBottom.Text)

                result% = PESetMargins(jobnum%, RepLeft%, RepRight%,
RepTop%, RepBottom%)

                ErrorTrap "SetMargins in FormatOptions", jobnum%

            End If

        Case "Cancel"

            MsgBox "Cancel was pressed - no changes will be made to the
print options", vbOKOnly + vbCritical, "Cancel Pressed"

    End Select

    Unload Options

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        ' Simplified version of the custom-link preview routine (no
custom buttons)

        result% = PEOutputToWindow(jobnum%, "Report Options Preview" &
Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0,
0)

        ErrorTrap "OutputtoWindow in FormatOptions", jobnum%

        result% = PEStartPrintJob(jobnum%, True)

        ErrorTrap "StartPrintJob in FormatOptions", jobnum%

        result% = 1

        Do While result% <> 0

            DoEvents

            DoEvents

            result% = PEGetWindowHandle(jobnum%)

        Loop

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in FormatOptions", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Options Complete!", vbOKOnly, "Operation Succeeded"

End Sub

ActiveX

Private Sub mnuFormatOptions_Click()

    Dim hwndPreviewWindow As Long

    If Not CRYSTAL_PRO Then

        MsgBox "Options are a Crystal Pro only feature.", vbOKOnly +
vbCritical, "Crystal Pro Only"

        Exit Sub

    End If

    CrystalReport1.ReportFileName = lblReportName.Caption ' Name from
label on sample form

    ' Load the Options form for filling in the option details of the
report

    Load Options

    CenterForm Sample, Options

    ' Load the title onto the form

    Options!txtTitle.Text = CrystalReport1.WindowTitle

    ' Get the print date for the report

    Options!txtDate.Text = Trim$(Str$(CrystalReport1.PrintMonth)) & "/"
& Trim$(Str$(CrystalReport1.PrintDay)) & "/" &
Trim$(Str$(CrystalReport1.PrintYear))

    ' Get print options

    ' If page range is set 1 and -1, set options page to All

    If CrystalReport1.PrinterStartPage <= 1 And
CrystalReport1.PrinterStopPage = -1 Then

        Options!txtPageFrom.Enabled = False

        Options!txtPageTo.Enabled = False

        Options!chkPageAll.Value = 1 ' Checked

    Else

        Options!txtPageFrom.Enabled = True

        Options!txtPageTo.Enabled = True

        Options!chkPageAll.Value = 0 ' Unchecked

        Options!txtPageFrom.Text = CrystalReport1.PrinterStartPage

        Options!txtPageTo.Text = CrystalReport1.PrinterStopPage

    End If

    Options!txtCopies.Text = CrystalReport1.PrinterCopies

    ' Set collation combo box

    Select Case CrystalReport1.PrinterCollation

        Case 0 ' Uncollated

            Options!cmbCollation.ListIndex = 1

        Case 1 ' Collated

            Options!cmbCollation.ListIndex = 2

        Case 2 ' Default

            Options!cmbCollation.ListIndex = 0

    End Select

    ' Get Margins

    Options!txtLeft.Text = CrystalReport1.MarginLeft

    Options!txtRight.Text = CrystalReport1.MarginRight

    Options!txtTop.Text = CrystalReport1.MarginTop

    Options!txtBottom.Text = CrystalReport1.MarginBottom

    ' Show the options form modally

    Options.Show 1

    ' Check what button was pressed

    Select Case Options.Tag

        Case "Ok"

            If MsgBox("Do you wish to modify the report options of this
print job?", vbYesNo + vbQuestion, "Change Report Options?") = vbYes Then

                ' Set the new report title

                CrystalReport1.WindowTitle = Trim$(Options!txtTitle.Text)

                ' Set print date if a valid date

                If IsDate(Options!txtDate.Text) Then

                    CrystalReport1.PrintYear =
Year(DateValue(Options!txtDate.Text))

                    CrystalReport1.PrintMonth =
Month(DateValue(Options!txtDate.Text))

                    CrystalReport1.PrintDay =
Day(DateValue(Options!txtDate.Text))

                End If

                ' Set print options

                If Options!chkPageAll.Value = 1 Then

                    CrystalReport1.PrinterStartPage = 1

                    CrystalReport1.PrinterStopPage = -1

                Else

                    CrystalReport1.PrinterStartPage =
Val(Options!txtPageFrom.Text)

                    CrystalReport1.PrinterStopPage =
Val(Options!txtPageTo.Text)

                End If

                CrystalReport1.PrinterCopies =
Val(Options!txtCopies.Text)

                Select Case Options!cmbCollation.Text

                    Case "Collated"

                        CrystalReport1.PrinterCollation = 0

                    Case "Uncollated"

                        CrystalReport1.PrinterCollation = 1

                    Case "Default"

                        CrystalReport1.PrinterCollation = 2

                End Select

                ' Set Margins

                CrystalReport1.MarginLeft = Val(Options!txtLeft.Text)

                CrystalReport1.MarginRight = Val(Options!txtRight.Text)

                CrystalReport1.MarginTop = Val(Options!txtTop.Text)

                CrystalReport1.MarginBottom = Val(Options!txtBottom.Text)

            End If

        Case "Cancel"

            MsgBox "Cancel was pressed - no changes will be made to the
print options", vbOKOnly + vbCritical, "Cancel Pressed"

    End Select

    Unload Options

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        CrystalReport1.Destination = 0 ' Window

        CrystalReport1.Action = 1 ' Print

        ErrorTrap "FormatOptions"

        hwndPreviewWindow = GetActiveWindow()

        Do While IsWindow(hwndPreviewWindow)

            DoEvents

        Loop

    End If

    ' Close the report

    CrystalReport1.ReportFileName = ""

    MsgBox "Options Complete!", vbOKOnly, "Operation Completed"

End Sub


VB Sample Code for PEGetVersion

DLL version

Private Sub mnuFileVersionDLL_Click()

    Dim result%, VersionNum As Single

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    VersionNum = PEVBGetVersion(PE_GV_DLL)

    MsgBox "DLL Version Number " & VersionNum, vbOKOnly + vbInformation,
"DLL Version"

    PECloseEngine

    MsgBox "DLL Version Complete!", vbOKOnly, "Operation Succeeded"

End Sub

Engine version

Private Sub mnuFileVersionEngine_Click()

    Dim result%, VersionNum As Single

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    VersionNum = PEVBGetVersion(PE_GV_ENGINE)

    MsgBox "Engine Version Number " & VersionNum, vbOKOnly +
vbInformation, "Engine Version"

    PECloseEngine

    MsgBox "Engine Version Complete!", vbOKOnly, "Operation Succeeded"

End Sub


VB Sample Code for sorting groups

Private Sub mnuSortingGroupSort_Click()

    Dim result%, jobnum%, mainjob%, fieldcount%, SortFieldN%,
fieldHandle&, fieldLength%, Direction%

    Dim FieldName$

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in SortingGroupSort", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in SortingGroupSort", mainjob%

    End If

    ' Count how many group sort fields there are

    fieldcount% = PEGetNGroupSortFields(jobnum%)

    If fieldcount% = -1 Then

        ' Something went wrong

        ErrorTrap "GetNGroupSortFields in SortingGroupSort", jobnum%

    ElseIf fieldcount% = 0 Then

        ' None!

        MsgBox "There are no group sort fields defined in this report.",
vbOKOnly + vbCritical, "No Group Sort Fields"

    Else

        ' There are Group Sort fields

        ' The sort order display form is loaded so that the list box can
be filled with sort fields

        Load SortOrder

        CenterForm Sample, SortOrder

        SortOrder.Caption = "Group Sort Order"

        ' Loop through the number of group sort fields determined by
PEGetNGroupSortFields

        For SortFieldN% = 0 To fieldcount% - 1

            ' Get the fieldhandle, length and sort direction

            result% = PEGetNthSortField(jobnum%, SortFieldN%,
fieldHandle&, fieldLength%, Direction%)

            ErrorTrap "GetNthSortField in SortingGroupSort", jobnum%

            ' Set chr$(0) into the fieldname string based on the length
retrieved in the preceding call

            ' NOTE! Failure to do this step results in GPFs

            FieldName$ = String$(fieldLength%, 0)

            ' crvbHandleToBstr fills the fieldname string with the name
of the sort field

            result% = crvbHandleToBstr(fieldHandle&, FieldName$,
fieldLength%)

            ErrorTrap "HandleToBstr for FieldName in SortingGroupSort",
jobnum%

            FieldName$ = Trim$(FieldName$)

            FieldName$ = Left$(FieldName$, Len(FieldName$) - 1)

            If Direction% = PE_SF_ASCENDING Then

                FieldName$ = FieldName$ & " (A)"

            ElseIf Direction% = PE_SF_DESCENDING Then

                FieldName$ = FieldName$ & " (D)"

            Else

                MsgBox "The direction flag has been set to an impossible
value. Execution must stop.", vbOKOnly + vbCritical, "Fatal Error"

                End

            End If

            ' The fieldname string is then inserted into the list box on
the sort order form

            SortOrder!lstSortList.AddItem FieldName$

        Next SortFieldN%

        ' Default to first item on list

        SortOrder!lstSortList.ListIndex = 0

        ' Once the list is complete, the sort order form is shown 1 '
Modally - execution in this module will stop

        ' until the sort order form is hidden (by pressing Ok or Cancel)

        SortOrder.Show 1 ' Modal

        ' Now that execution has returned, check what button was pressed
and react accordingly

        Select Case SortOrder.Tag

            Case "Ok"

                If MsgBox("Do you want to change the group sort order of
this print job?", vbYesNo + vbQuestion, "Change Group Sort Order?") =
vbYes Then

                    ' Make changes to the print job group sort order -
note that this has no permanent affect on the report

                    ' Changes made at the API level cannot be stored in
the report

                    For SortFieldN% = 0 To SortOrder!lstSortList.ListCount
- 1

                        ' Pull the direction of the group sort field item
first and store it

                        If Right$(SortOrder!lstSortList.List(SortFieldN%),
3) = "(A)" Then

                            Direction% = PE_SF_ASCENDING

                        Else

                            Direction% = PE_SF_DESCENDING

                        End If

                        ' Copy the name of the group sort field from the
list box

                        FieldName$ =
SortOrder!lstSortList.List(SortFieldN%)

                        ' Clip the direction off

                        FieldName$ = Left$(FieldName$, Len(FieldName$) -
4) & Chr$(0)

                        ' Set the group sort field

                        result% = PESetNthGroupSortField(jobnum%,
SortFieldN%, FieldName$, Direction%)

                        ErrorTrap "SetNthGroupSortField in
SortingGroupSort", jobnum%

                    Next SortFieldN%

                End If

            Case "Cancel"

                MsgBox "Cancel was pressed on the Sort Order form. The
group sort order of the print job will not be changed.", vbOKOnly +
vbInformation, "Cancel Pressed"

        End Select

        ' Finished with the sort order form - unload it

        Unload SortOrder

        ' Offer opportunity to see what you did to the report

        If MsgBox("Do you want to preview the report?", vbYesNo +
vbQuestion, "Preview Report?") = vbYes Then

            ' Simplified version of the custom-link preview routine (no
custom buttons)

            result% = PEOutputToWindow(jobnum%, "Group Sort Order
Demonstration Preview" & Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT, 0, 0)

            ErrorTrap "OutputtoWindow in SortingGroupSort", jobnum%

            result% = PEStartPrintJob(jobnum%, True)

            ErrorTrap "StartPrintJob in SortingGroupSort", jobnum%

            result% = 1

            Do While result% <> 0

                DoEvents

                DoEvents

                result% = PEGetWindowHandle(jobnum%)

            Loop

        End If

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in SortingGroupSort", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Sort Groups Complete!", vbOKOnly, "Operation Succeeded"

End Sub

ActiveX

Private Sub mnuSortingGroupSort_Click()

    Dim SortFieldN As Integer

    Dim FieldName As String, SortDirection As String

    Dim hwndPreviewWindow As Long

    CrystalReport1.ReportFileName = lblReportName.Caption ' Name from
label on sample form

    ' Set up endless loop (only ends with an Exit Do) for editing
multiple sort fields

    Do While True

        FieldName = InputBox("Enter group sort field to edit. Press
Cancel to end editing of group sort fields:", "Enter Group Sort Field
Number", "0")

        ' if a zero length string, then Cancel was pressed, exit the loop

        If FieldName = "" Then Exit Do

        ' Otherwise a sort field number was entered, convert it

        SortFieldN = Val(FieldName)

        ' Get FieldName

        FieldName = InputBox("Enter field name(s) for the group sort
field. Press Cancel to end editing of group sort fields. Field names must
be encased in braces:", "Enter Group Sort Field Name:", "{}")

        ' if a zero length string, then Cancel was pressed, exit the loop

        If FieldName = "" Then Exit Do

        ' Get Sort Direction

        SortDirection = InputBox("Enter the sort direction. Press Cancel
to end editing of group sort fields. Press 'A' for Ascending, 'D' for
Descending:", "Enter Sort Direction", "A")

        If SortDirection = "" Then Exit Do

        If SortDirection = "A" Then SortDirection = "+" Else
SortDirection = "-"

        ' Load sort field with data input

        CrystalReport1.GroupSortFields(SortFieldN) = SortDirection &
FieldName

    Loop

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        CrystalReport1.Destination = 0 ' Window

        CrystalReport1.Action = 1 ' Print

        ErrorTrap "SortingGroupSort"

        hwndPreviewWindow = GetActiveWindow()

        Do While IsWindow(hwndPreviewWindow)

            DoEvents

        Loop

    End If

    ' Close the report

    CrystalReport1.ReportFileName = ""

    MsgBox "Sort Groups Complete!", vbOKOnly, "Operation Completed"

End Sub


VB Sample Code for sorting records

Private Sub mnuSortingSortFields_Click()

    Dim result%, jobnum%, mainjob%, fieldcount%, SortFieldN%,
fieldHandle&, fieldLength%, Direction%

    Dim FieldName$

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in SortingSortFields", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in SortingSortFields", mainjob%

    End If

    ' Count how many sort fields there are

    fieldcount% = PEGetNSortFields(jobnum%)

    If fieldcount% = -1 Then

        ' Something went wrong

        ErrorTrap "GetNSortFields in SortingSortFields", jobnum%

    ElseIf fieldcount% = 0 Then

        ' None!

        MsgBox "There are no sort fields defined in this report.",
vbOKOnly + vbCritical, "No Sort Fields"

    Else

        ' There are sort fields

        ' The sort order display form is loaded so that the list box can
be filled with sort fields

        Load SortOrder

        CenterForm Sample, SortOrder

        SortOrder.Caption = "Sort Order"

        ' Loop through the number of sort fields determined by
PEGetNSortFields

        For SortFieldN% = 0 To fieldcount% - 1

            ' Get the fieldhandle, length and sort direction

            result% = PEGetNthSortField(jobnum%, SortFieldN%,
fieldHandle&, fieldLength%, Direction%)

            ErrorTrap "GetNthSortField in SortingSortFields", jobnum%

            ' Set spaces into the fieldname string based on the length
retrieved in the preceding call

            ' NOTE! Failure to do this step results in General Protection
Faults

            FieldName$ = String$(fieldLength%, 0)

            ' crvbHandleToBstr fills the fieldname string with the name
of the sort field

            result% = crvbHandleToBstr(fieldHandle&, FieldName$,
fieldLength%)

            ErrorTrap "HandleToBstr for FieldName in SortingSortFields",
jobnum%

            FieldName$ = Trim$(FieldName$)

            FieldName$ = Left$(FieldName$, Len(FieldName$) - 1)

            If Direction% = PE_SF_ASCENDING Then

                FieldName$ = FieldName$ & " (A)"

            ElseIf Direction% = PE_SF_DESCENDING Then

                FieldName$ = FieldName$ & " (D)"

            Else

                MsgBox "The direction flag has been set to an impossible
value. Execution must stop.", vbOKOnly + vbCritical, "Fatal Error"

                End

            End If

            ' The fieldname string is then inserted into the list box on
the sort order form

            SortOrder!lstSortList.AddItem FieldName$

        Next SortFieldN%

        ' Default to first item on list

        SortOrder!lstSortList.ListIndex = 0

        ' Once the list is complete, the sort order form is shown 1 '
Modally - execution in this module will stop

        ' until the sort order form is hidden (by pressing Ok or Cancel)

        SortOrder.Show 1 ' Modal

        ' Now that execution has returned, check what button was pressed
and react accordingly

        Select Case SortOrder.Tag

            Case "Ok"

                If MsgBox("Do you want to change the sort order of this
print job?", vbYesNo + vbQuestion, "Change Sort Order?") = vbYes Then

                    ' Make changes to the print job sort order - note that
this has no permanent affect on the report

                    ' Changes made at the API level cannot be stored in
the report

                    For SortFieldN% = 0 To SortOrder!lstSortList.ListCount
- 1

                        ' Pull the direction of the sort field item first
and store it

                        If Right$(SortOrder!lstSortList.List(SortFieldN%),
3) = "(A)" Then

                            Direction% = PE_SF_ASCENDING

                        Else

                            Direction% = PE_SF_DESCENDING

                        End If

                        ' Copy the name of the sort field from the list box

                        FieldName$ =
SortOrder!lstSortList.List(SortFieldN%)

                        ' Clip the direction off and add null

                        FieldName$ = Left$(FieldName$, Len(FieldName$) -
4) & Chr$(0)

                        ' Set the sort field

                        result% = PESetNthSortField(jobnum%, SortFieldN%,
FieldName$, Direction%)

                        ErrorTrap "SetNthSortField in SortingSortFields",
jobnum%

                    Next SortFieldN%

                End If

            Case "Cancel"

                MsgBox "Cancel was pressed on the Sort Order form. The
sort order of the print job will not be changed.", vbOKOnly +
vbInformation, "Cancel Pressed"

        End Select

        ' Finished with the sort order form - unload it

        Unload SortOrder

        ' Offer opportunity to see what you did to the report

        If MsgBox("Do you want to preview the report?", vbYesNo +
vbQuestion, "Preview Report?") = vbYes Then

            ' Simplified version of the custom-link preview routine (no
custom buttons)

            result% = PEOutputToWindow(jobnum%, "Sort Order Demonstration
Preview" & Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, 0, 0)

            ErrorTrap "OutputtoWindow in SortingSortFields", jobnum%

            result% = PEStartPrintJob(jobnum%, True)

            ErrorTrap "StartPrintJob in SortingSortFields", jobnum%

            result% = 1

            Do While result% <> 0

                DoEvents

                DoEvents

                result% = PEGetWindowHandle(jobnum%)

            Loop

        End If

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in SortingSortFields", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Sort Fields Complete!", vbOKOnly, "Operation Succeeded"

End Sub

ActiveX

Private Sub mnuSortingSortFields_Click()

    Dim SortFieldN As Integer

    Dim FieldName As String, SortDirection As String

    Dim hwndPreviewWindow As Long

    CrystalReport1.ReportFileName = lblReportName.Caption ' Name from
label on sample form

    ' Set up endless loop (only ends with an Exit Do) for editing
multiple sort fields

    Do While True

        FieldName = InputBox("Enter sort field to edit. Press Cancel to
end editing of sort fields:", "Enter Sort Field Number", "0")

        ' if a zero length string, then Cancel was pressed, exit the loop

        If FieldName = "" Then Exit Do

        ' Otherwise a sort field number was entered, convert it

        SortFieldN = Val(FieldName)

        ' Get FieldName

        FieldName = InputBox("Enter field name for sort field. Press
Cancel to end editing of sort fields. Field names must be encased in
braces:", "Enter Field Name:", "{}")

        ' if a zero length string, then Cancel was pressed, exit the loop

        If FieldName = "" Then Exit Do

        ' Get Sort Direction

        SortDirection = InputBox("Enter the sort direction. Press Cancel
to end editing of sort fields. Press 'A' for Ascending, 'D' for
Descending.", "Enter Sort Direction", "A")

        If SortDirection = "" Then Exit Do

        If SortDirection = "A" Then SortDirection = "+" Else
SortDirection = "-"

        ' Load sort field with data input

        CrystalReport1.SortFields(SortFieldN) = SortDirection & FieldName

    Loop

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        CrystalReport1.Destination = 0 ' Window

        CrystalReport1.Action = 1 ' Print

        ErrorTrap "SortingSortFields"

        hwndPreviewWindow = GetActiveWindow()

        Do While IsWindow(hwndPreviewWindow)

            DoEvents

        Loop

    End If

    ' Close the report

    CrystalReport1.ReportFileName = ""

    MsgBox "Sort Fields Complete!", vbOKOnly, "Operation Completed"

End Sub


VB Code for working with stored procedure parameters

Private Sub mnuTableParameters_Click()

    Dim result%, jobnum%, mainjob%, paramCount%, paramN%, textHandle&,
TextLength%

    Dim paramText$

    Dim TableType As PETableType, LogOnInfo As PELogOnInfo

    ' Modifying table parameters is a feature available only to Crystal
Pro

    If Not CRYSTAL_PRO Then

        MsgBox "Options are a Crystal Pro only feature.", vbOKOnly +
vbCritical, "Crystal Pro Only"

        Exit Sub

    End If

    result% = PEOpenEngine()

    If result% = 0 Then

        MsgBox "Could not start the report engine. Execution must halt.",
vbOKOnly + vbCritical, "Serious Error"

        End

    End If

    jobnum% = PEOpenPrintJob(lblReportName.Caption) ' Name from label on
sample form

    ErrorTrap "OpenPrintJob in TableParameters", jobnum%

    ' Subreport check - if a subreport is currently selected on the main
form, jobnum% becomes the subreport

    If lblSubreportName.Visible Then

        mainjob% = jobnum%

        jobnum% = PEOpenSubreport(mainjob%, lblSubreportName.Caption)

        ErrorTrap "OpenSubReport in TableParameters", mainjob%

    End If

    ' Parameters only exist when the table type is SQL - standard table
types don't have the queries

    ' Note that access databases can be connected as a standard type or
as an SQL type through ODBC

    ' This example is not designed to handle multiple data sources on a
single report - it presumes

    ' that all tables are standard or SQL, and if SQL, from one database

    ' Define the size of the structures

    TableType.StructSize = PE_SIZEOF_TABLE_TYPE

    LogOnInfo.StructSize = PE_SIZEOF_LOGON_INFO

    result% = PEGetNthTableType(jobnum%, 0, TableType)

    ErrorTrap "GetNthTableType in TableParameters", jobnum%

    If TableType.DBType = PE_DT_STANDARD Then

        MsgBox "SQL Queries are only available for SQL databases. This
report is attached to a standard database. Select a different report.",
vbOKOnly + vbCritical, "SQL Databases Only!"

    Else

        ' Now that it is confirmed that this is an SQL database, we will
attempt to get logon information

        ' from the crPEGetNthTableLogOnInfo call - this data will be
offered as default for the Logon Server

        ' parameters

        result% = crPEGetNthTableLogOnInfo(jobnum%, 0,
logOnInfo.ServerName, logOnInfo.DatabaseName, logOnInfo.UserID)

        ErrorTrap "GetNthTableLogOnInfo in TableParameters", jobnum%

        ' Get the fields needed for the LogOn Server call from the user,
defaulting with the data

        ' from the TableLogOnInfo call

        LogOnInfo.ServerName = InputBox$("Enter the name of the Server:",
"Server Name", LogOnInfo.ServerName) & Chr$(0)

        LogOnInfo.DatabaseName = InputBox$("Enter the name of the
Database:", "Database Name", LogOnInfo.DatabaseName) & Chr$(0)

        LogOnInfo.UserID = InputBox("Enter the User ID:", "User ID",
LogOnInfo.UserID) & Chr$(0)

        LogOnInfo.Password = InputBox("Enter the Password:", "Password",
LogOnInfo.Password) & Chr$(0)

        ' Attempt to log on server using parameters

        result% = crPELogOnServer(tableType.DLLName,
logOnInfo.ServerName, logOnInfo.DatabaseName, logOnInfo.UserID,
logOnInfo.Password)

        ErrorTrap "LogOnServer in TableParameters", jobnum%

        ' Get number of parameters

        paramCount% = PEGetNParams(jobnum%)

        ErrorTrap "GetNParams in TableParameters", jobnum%

        If paramCount% < 1 Then

            MsgBox "There are no parameters in this report. Execution must
halt.", vbOKOnly + vbCritical, "No Parameters"

        Else

            ' If there are parameters, load them into the sections form

            Load Sections

            CenterForm Sample, Sections

            Sections.Tag = "Query Parameter List"

            For paramN% = 0 To paramCount% - 1

                ' Get parameter

                result% = PEGetNthParam(jobnum%, paramN%, textHandle&,
TextLength%)

                ' Set chr$(0) into the fieldname string based on the
length retrieved in the preceding call

                ' NOTE! Failure to do this step results in General
Protection Faults

                paramText$ = String$(TextLength%, 0)

                ' crvbHandleToBstr fills the fieldname string with SQL
Query text

                result% = crvbHandleToBstr(textHandle&, paramText$,
TextLength%)

                ErrorTrap "HandleToBstr for paramText in TableParameters",
jobnum%

                ' Put parameter into sections form

                Sections!lstSections.AddItem paramText$

            Next paramN%

            ' Show form 1 ' Modally

            Sections.Show 1 ' Modal

            Select Case Sections.Tag

                Case "Ok"

                    If MsgBox("Set changes to parameters into print job?",
vbYesNo + vbQuestion, "Change Parameters?") = vbYes Then

                        ' Set up loop to set parameter changes into print
job

                        For paramN% = 0 To Sections!lstSections.ListCount
- 1

                            ' Get parameter from list box on sections form,
add null to end for termination

                            paramText$ = Sections!lstSections.List(paramN%)
& Chr$(0)

                            result% = PESetNthParam(jobnum%, paramN%,
paramText$)

                            ErrorTrap "SetNthParam in TableParameters",
jobnum%

                        Next paramN%

                    End If

                Case "Edit"

Sections!lstSections.List(Sections!lstSections.ListIndex) =
InputBox$("Enter parameter data for this parameter:", "Enter Parameter
Data", Sections!lstSections.List(Sections!lstSections.ListIndex))

            End Select

            Unload Sections

        End If

        ' Log off Server

        result% = crPELogOffServer(tableType.DLLName,
logOnInfo.ServerName, logOnInfo.DatabaseName, logOnInfo.UserID,
logOnInfo.Password)

        ErrorTrap "LogOffServer in TableParameters", jobnum%

    End If

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        ' Simplified version of the custom-link preview routine (no
custom buttons)

        result% = PEOutputToWindow(jobnum%, "Parameters Demonstration
Preview" & Chr$(0), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, 0, 0)

        ErrorTrap "OutputtoWindow in TableParameters", jobnum%

        result% = PEStartPrintJob(jobnum%, True)

        ErrorTrap "StartPrintJob in TableParameters", jobnum%

        result% = 1

        Do While result% <> 0

            DoEvents

            DoEvents

            result% = PEGetWindowHandle(jobnum%)

        Loop

    End If

    ' Close print job and engine

    ' Subreport check - if a subreport is currently open, call
PreviewReport to offer a chance to

    ' preview the main report, then close the subreport and main report

    If lblSubreportName.Visible Then

        PreviewReport mainjob%

        result% = PECloseSubreport(jobnum%)

        ErrorTrap "CloseSubReport in TableParameters", mainjob%

        PEClosePrintJob mainjob%

    Else

        PEClosePrintJob jobnum%

    End If

    PECloseEngine

    MsgBox "Query Parameters Complete!", vbOKOnly, "Operation Succeeded"

End Sub

ActiveX

Private Sub mnuTableParameters_Click()

    Dim ParamN As Integer, GetParamN As String

    Dim hwndPreviewWindow As Long

    ' Modifying table parameters is a feature available only to Crystal
Pro

    If Not CRYSTAL_PRO Then

        MsgBox "Options are a Crystal Pro only feature.", vbOKOnly +
vbCritical, "Crystal Pro Only"

        Exit Sub

    End If

    CrystalReport1.ReportFileName = lblReportName.Caption ' Name from
label on sample form

    ' Set up endless loop (only ends with an Exit Do) for editing
multiple parameters

    Do While True

        GetParamN = InputBox("Enter parameter number to edit. Press
Cancel to end editing of parameters:", "Enter Parameter Number", "0")

        ' if a zero length string, then Cancel was pressed, exit the loop

        If GetParamN = "" Then Exit Do

        ' Otherwise a parameter number was entered, display a input box
for the parameter

        ParamN = Val(GetParamN)

        GetParamN = InputBox("Enter value for parameter number " & ParamN
& ". Press Cancel to abort editing of parameter:", "Enter Parameter",
CrystalReport1.StoredParamProc(ParamN))

        If GetParamN = "" Then Exit Do

        CrystalReport1.StoredProcParam(ParamN) = GetParamN

    Loop

    ' Offer opportunity to see what you did to the report

    If MsgBox("Do you want to preview the report?", vbYesNo + vbQuestion,
"Preview Report?") = vbYes Then

        CrystalReport1.Destination = 0 ' Window

        CrystalReport1.Action = 1 ' Print

        ErrorTrap "TableParameters"

        hwndPreviewWindow = GetActiveWindow()

        Do While IsWindow(hwndPreviewWindow)

            DoEvents

        Loop

    End If

    ' Close the report

    CrystalReport1.ReportFileName = ""

    MsgBox "Query Parameters Complete!", vbOKOnly, "Operation Completed"

End Sub


Active Data

This section provides information on using active data in the Crystal Reports Development environment. Three areas are covered; the active data driver, Crystal Data Object, and Crystal Data Source Type Library. By reading these sections you will learn how to create active data reports, create recordsets, and connect to the datasource through the Report Designer Component automation server.

Click the appropriate link to jump to that section:

  • Active Data Driver
  • Crystal Data Object
  • Crystal Data Source Type Library


Active Data Driver

Modern Visual Basic applications often use advanced ActiveX components to connect to data sources. These data sources may include Data Access Objects (DAO), Remote Data Objects (RDO), OLE DB providers, such as ActiveX Data Objects (ADO), or the Visual Basic data controls. Using the Active Data Driver for Crystal Reports, you can design reports for your Visual Basic applications that use these same ActiveX data sources. The Active Data Driver also supports Crystal Data Objects (CDO) and the Crystal Data Source Type Library. For more information on RDO, DAO, and ADO, refer to Microsoft documentation. For information on the Data Control, refer to your Visual Basic documentation. For information on CDO, see Crystal Data Object. For information on the Crystal Data Source Type Library, see Crystal Data Source Type Library.

Occasionally, you may also need to create a report when the data source is not actually available at design time. Highly dynamic data may only be available at runtime. In such cases, the Active Data Driver supports the use of Data definition files, tab separated text files that define the fields in a data source but not the actual data.

Normally, developing applications using the Report Designer Component requires designing and saving one or more report files in advance to be accessed by the application at runtime. This process requires that the programmer has access to the data during design time, and that the application, upon installation, also installs whatever database drivers and files are required to make sure the reports can connect to the required data.

An alternative to runtime connectivity, of course, is to save data with the report files. The data is neatly packaged and available whenever the report is requested from your custom application. However, saving data with a report increases the file size of the report, wasting disk space. Furthermore, this technique produces a static report file in which the data cannot be updated without connectivity to the database.

The Crystal Active Data Driver allows you to create report files at design time without specifying an actual data source. Instead, the report is based on a data definition file, an ASCII text file with place holders to represent database fields. At runtime, you add code to your application to specify the actual source of data for the report.

The following topics are discussed in this section:

  • Data Definition Files
  • Using the Active Data Driver
  • Creating Data Definition Files
  • Using ActiveX Data Sources at Design Time


Data Definition Files

A report file designed using a data definition file, instead of a specific database or ODBC data source, contains information about the kind of data to place in the report instead of information about an actual data source. It looks for field types, rather than actual fields. For an example of a data definition file, refer to the file ORDERS.TTX installed in the \Program Files\Seagate Software\Crystal Reports directory.

At design time, you create your report based on the data definition file. Previewing or printing the report at design time has little value except to format field placement and style. Since there is no real data in the text file, you cannot preview or print any data at design time.

Note: You can add sample data to the data definition file so that values will appear for each field in the Preview Tab at design time, but the values will be identical for all records, and grouping will not be available.

At runtime, your application opens the report file, just as it would any other report file. Instead of simply formatting and printing the file at runtime, though, you change the data source pointed at by the Crystal Active Data Driver, which is the data definition file, to a Recordset or Rowset object for an ActiveX data source such as ADO, RDO, DAO, or the Crystal Data Sources (see Crystal Data Object), and the Crystal Data Source Type Library (see Crystal Data Source Type Library).

Once the Crystal Active Data Driver obtains the Recordset from the runtime data source, the Report Designer Component can generate the actual report using existing data. The entire process saves you time designing reports and produces reports that are much more flexible and portable at runtime. For more information on data definition files, see Creating Data Definition Files.


Using the Active Data Driver

Designing and generating reports using the Crystal Active Data Driver is a straightforward process, but requires several specific steps:

  • Select the design time data source
  • Design the Report
  • Obtain a Recordset from the Runtime Data Source
  • Open the Report
  • Pass the Recordset to the Active Data Driver
  • Print the Report

The following sections demonstrate this process using the Crystal Active Data Driver with the Report Designer Component Automation Server in Visual Basic 6.0.


Select the design time data source

When designing a report for your Visual Basic application, you can specify any ActiveX data source using the Active Data Driver, or you can specify a data definition file so that the actual data is specified at runtime only. The following example uses the sample data definition file included with Crystal Reports:

  1. Click New Report in the Crystal Reports Welcome dialog box, or click the New button on the Crystal Reports toolbar.
  2. In the Crystal Report Gallery dialog box click Using the Report Expert. In this example, you can click Standard from the Choose an Expert box. Then Click OK.
  3. In the Standard Report Expert Dialog box click Database.
  4. In the Data Explorer dialog box:
      • expand More Data Sources
      • expand Active Data
      • expand Active Data (ADO).
  5. In the Select Data Source dialog box click the ODBC (ADO) option, select Xtreme Sample Database from the drop-down list, and then click OK.
  6. In the Data Explorer dialog box click Add.
  7. In the Select Recordset dialog box select Orders from the Object list, and then click OK.
  8. In the Data Explorer dialog box click Close. The Orders table appears as ado in the Tables available for report box, under the data tab, in the Standard Report Expert dialog box.

Note: For information on specifying an OLE DB provider or other ActiveX data source at design time, see Using ActiveX Data Sources at Design Time.


Design the Report

Once you have selected a data definition file or an ActiveX data source, you can design your report just as you would design any other report.

  1. Click the Fields Tab of the Standard Report Expert.

    The data definition file orders appears as a database table in the Database Fields list box. Each of the fields defined in orders.ttx appears as a field in the orders table.

  2. Add fields to your report just as you would normally add fields to a report using the Standard Report Expert.
  3. Continue designing the report using the Standard Report Expert. When finished, click Design Report. Since the report is based on a data definition file, there is no point in previewing it at this time.
  4. Apply any formatting or other changes that you feel are necessary to fine-tune the look of your report. Save the report when finished.

Note: Before saving your report, be sure to turn off the Save Data with Report option under the File menu. The sample data stored with the data definition file is unnecessary at runtime, and will only increase the size of your report file.


Obtain a Recordset from the Runtime Data Source

Once you have selected a data source or data definition file and designed a report based on that data source or file, you can begin programming your Visual Basic application to obtain a recordset from an ActiveX data source, open the report file, set the report file to use the recordset object from the ActiveX data source, then print or export the report file. This process requires using the functionality of the Crystal Active Data Driver in conjunction with the Report Designer Component or one of the other Crystal Reports development tools. See the "Visual Basic Solutions" chapter in the Crystal Reports Technical Reference Guide, or the Crystal Reports Developer's Help (CrystalDevHelp.chm) for more information on the other Crystal Reports development tools.

The following tutorials use the Report Designer Component Automation Server in Visual Basic 6.0. This section assumes a familiarity with the Report Designer Component Automation Server. If you need more information on how to use the automation server, see the Report Designer Component Object Model.

To begin, you must obtain a Recordset object from a runtime ActiveX data source. This data source can be opened through DAO, RDO, ADO, the Visual Basic Data Control, Crystal Data Objects (CDO), or a class that implements the Crystal Data Source Type Library. For information on DAO, RDO, and ADO, refer to Microsoft documentation. For information on the Visual Basic Data Control, refer to your Visual Basic documentation. For information on CDO, see Crystal Data Object . For information on the Crystal Data Source Type Library, see Crystal Data Source Type Library.

This tutorial creates a Recordset object from the Orders table of the XTREME.MDB sample database using DAO. The Recordset concept is used by DAO, ADO, and the Crystal Data Source Type Library. If you are using RDO, you will need to obtain a rdoResultSet object. If you are using CDO, you will need to obtain a Rowset object (see Crystal Data Object).

Note: You must add the Data Access Objects component to your Visual Basic project before performing the following steps. For instructions on using DAO with Visual Basic, refer to your Visual Basic documentation.

  • Declare variables for the Database and Recordset objects in your Visual Basic application. This can be handled in the declarations section of a form or module. Use code similar to this:

    Dim db As New DAO.Database
    Dim rs As DAO.Recordset

  • Obtain a Database object from the Xtreme database.

    Set db = DBEngine.Workspaces(0).OpenDatabase( _
    "c:\Program Files\Seagate Software\Crystal Reports\xtreme.mdb")

  • Obtain a Recordset object from the Orders table of the Xtreme database.

    Set rs = db.OpenRecordset("Orders", dbOpenTable)


Open the Report

Once you have obtained a Recordset object, you can begin working with the report file you created earlier. This example uses the Report Designer Component Automation Server to open a report file.

Note: You must add the Report Designer Component Automation Server component to your Visual Basic project before performing the following steps. For complete information on using the Automation Server, see Crystal Report Engine Automation Server.

  • Declare variables for the Application and Report objects that you will obtain from the Report Designer Component Object Library in the automation server. This can be handled in the declarations section of a form or module.

Dim CRXApplication As New Craxdrt.Application
Dim CRXReport As Craxdrt.Report
  • Obtain a Report object by opening the report file you created earlier. This example uses the file ORDERS.RPT.

    Set CRXReport = CRXApplication.OpenReport("c:\reports\Orders.rpt", 1)


Pass the Recordset to the Active Data Driver

The Recordset object gets passed to the Active Data Driver through the SetDataSource method of the Database object in the Report Designer Component Object Library. You must first obtain a Database object from the Report object, then you must use the SetDataSource method to set the report to point at the recordset object for your Active data source. The Report Designer Component Automation Server uses the Active Data Driver itself to replace the data definition file, at runtime, with the Active data source.

The following code demonstrates how to obtain a Database object from the Report object:

Dim CRXDatabase As Craxdrt.Database
Set CRXDatabase = CRXReport.Database

Once you have a Database object for the Report object, you can pass the Active data source to the Report object using the SetDataSource method. This method requires three parameters. The first is the data source itself. The second parameter is a value indicating that the data source you are passing to the report is an ActiveX data source. This value must be 3. The third is the table you are passing the data source to. Since you should only have one table defining the structure of the recordset , this should always be 1. For example:

CRXDatabase.SetDataSource rs, 3, 1


Print the Report

Now that the data source for the report has been set to the DAO Recordset, you can print, preview, or export the report normally. For instance, the following code prints the report to the default printer:

CRXReport.PrintOut

Once the data source has been set in the report object, runtime reporting can proceed normally. All features of the Report Designer Component are available to you. See Report Designer Component Object Model for more information.


Creating Data Definition Files

A data definition file is a tab-separated text file that contains information about field names, field types, and sample field data. Field names used in the data definition file must match the field names that will appear in the ActiveX data source that is specified at runtime. Field type information indicates the type of data in each field (string, numeric, date, etc.) and, if it is a string field, the maximum length of the string. Finally, sample field data is simply sample data that Crystal Reports can display in the preview window while you design the report.

For complete information on creating data definition files, see Creating Data Definition Files. Crystal Reports installs a sample data definition file in the \Program Files\Seagate Software\Crystal Reports directory on your system. This file is named ORDERS.TTX and can be used with the Orders table in the XTREME.MDB sample database or the Xtreme sample data ODBC data source that was created when you installed Crystal Reports.

The following is an example of how fields are defined in a data definition file:

Order ID            Long        1
Customer Name            String    50    Sample string value
Order Date            Date        Jan 5, 2000
Order Amount            Currency        $1.00

The Active Data Driver supports the following data types in a data definition file:

Data Type Description

BLOB

Fields that contain bitmap images.

Boolean

True/False Boolean value.

Byte

8-bit integer value.

Currency

64-bit floating-point value that can include a currency or percent sign.

Date

Any date/time value. Examples include:

  • Jan 5, 1999
  • 07/11/97 5:06:07
  • 07/11/97
  • 23:30:01

Long, int32

32-bit integer value.

Memo

Any string value over 254 characters long. You must indicate the maximum number of characters for the string.

Number

64-bit floating-point value.

Short, int16

16-bit integer value.

String

Any string value under 254 characters long, such as a name, description, or identification number that is not meant to be interpreted numerically. You must indicate the maximum number of characters for the string.

Note: The data type BLOB is supported when connecting to RDO, ADO, DAO and the data control at runtime but not when connecting to CDO.

Although data definition files can be created manually using a text editor such as Notepad, Crystal Reports provides tools for simplifying the process. Each tool has its advantages. Review the process for using each tool described below to determine which best suits your own environment and development process.

  • Database Definition Tool
  • Active Data Driver Functions


Database Definition Tool

The Database Definition Tool is available from the Select Data Source dialog box when you begin designing a report based on the Active Data Driver. This tool allows you to design a data definition file as the first step of designing your report. From the Standard Report Expert:

  1. In the Standard Report Expert click Database.
  2. In the Data Explorer dialog box:
      • expand More Data Sources
      • expand Active Data
      • expand Active Data (Field Definitions Only).
  3. In the Select Data Source dialog box click New to create a new data definition file.

    The Database Definition Tool appears.

  4. Use the Database Definition Tool to create fields for your data definition file.

    Use the controls to enter field names, field types, and sample data that will appear in the Crystal Reports Preview Tab. If you select String as the field type, you will also be asked to specify a maximum string length.

  5. Click Add to add each new field to your data definition file. Each field appears in the list box at the bottom of the Database Definition Tool.
  6. Continue adding as many fields as necessary for your data definition file by entering the information in the controls of the Database Definition Tool, and clicking Add each time.
  7. You can delete a field that you have created by selecting the field in the list box and clicking Delete.
  8. Click the Close button in the upper right of the Database Definition Tool dialog box when you are finished designing your data definition file. A message appears asking if you want to save the data definition file.
  9. Click Yes, and a Save File As dialog box appears.
  10. Save the data definition file where it can be accessed by your report file. When finished, the new data definition file will appear in the Data Definition text box in the Select Data Source dialog box.
  11. Continue creating your report.


Active Data Driver Functions

The Active Data Driver (P2SMON.DLL) is a standard dynamic link library that is normally used by Crystal Reports (or the Report Designer Component) to access ActiveX data sources such as DAO and ADO. The DLL is installed, by default, in your \WINDOWS\SYSTEM directory. In addition, the Active Data Driver exports functions that can be used at runtime from within your application to dynamically design a data definition file based on your data source, and a report file based on the data definition file. These functions are available to any development environment that supports DLL function calls.

Note: To use the functions in the Active Data Driver DLL, you must declare the functions first. Refer to your Visual Basic documentation for information on declaring DLL functions. See The Crystal Active Data Driver Reference for information about declaring the Active Data Driver functions.

To use the Active Data Driver Functions from Visual Basic
  1. Obtain a valid Recordset object from your DAO, ADO, or Data Control data source, or a valid Rowset object using CDO.
  2. Call the function CreateReportOnRuntimeDS to create a data definition file based on your Recordset or Rowset object. For example:
CreateReportOnRuntimeDS(daoRs, "c:\reports\orders.rpt",

    "c:\reports\orders.ttx", True, False)

This example creates a data definition file named ORDERS.TTX, then creates a simple report file based on this data definition file and names it ORDERS.RPT. If the last argument is set to True, Crystal Reports, if installed on the system, will open automatically on the user's machine, allowing them to make changes to the report file.

Notice that the first argument is a DAO Recordset object. If you are using this function in a language such as C or C++, you would pass a pointer to an IUnknown derived interface to the Recordset.

Note: See The Crystal Active Data Driver Reference for complete information on the functions provided by the Active Data Driver.


Using ActiveX Data Sources at Design Time

The Active Data Driver is intended to allow reports to be based on ActiveX data sources such as ADO and DAO. Data definition files allow you to avoid specifying an actual data source until runtime. However, you may often need to simply specify an ADO data source at design time for the report.

The Select Data Source dialog opens when you select one of the active data folders in the More Data Sources\Active Data folder in the Data Explorer. This dialog box provides four options for selecting a data source to use in your report: specify an ODBC data source for ADO or RDO, specify an ADO connection string for OLE DB, specify a DAO recordset, or specify a data definition file. The Data Definition option has been thoroughly discussed earlier in this section. The remainder of this section will discuss selecting an ADO, RDO, or DAO data source.

The following topics are discussed in this section:

  • ODBC with ADO and RDO
  • ADO and OLE DB
  • DAO


ODBC with ADO and RDO

  1. Click the ODBC option in the Select Data Source dialog box.

    This option allows you to connect to an ODBC data source through ADO or RDO. The currently selected data objects technology appears in parentheses next to the ODBC option.

  • Use the drop-down list to select an ODBC data source that is available on your system.
  • Click the New button to create a new ODBC data source. Refer to Microsoft ODBC documentation for information on creating ODBC data sources.
  • Click the Advanced button to select ADO or RDO as the data objects technology used. This should match the technology used in your Visual Basic application.
  2. After you select your data source and data objects technology, you can click Next in the Select Data Source dialog box.

    The Select Recordset dialog box appears.

  3. If the ODBC data source requires log on information, specify a user name and password to log on.
  4. Determine if you want to create a Recordset or Resultset using an object available from your data source, such as a database table, or if you prefer to specify a SQL statement. Select the appropriate option in the Recordset section of the Select Recordset dialog box.

    Note: For simplicity, RDO Resultsets are also referred to as Recordsets in this dialog box.

  5. If you want to connect to a database object, use the Object Type drop-down list box to select the type of database object, such as a Table, then select the object itself from the Object drop-down list box.
  6. If you want to obtain a Recordset using a SQL statement, write the SQL statement in the text box provided, or click Build to use the Microsoft Query application and Query Wizard to visually design your SQL statement.
  7. Click Finish in the Select Recordset dialog box. Either ado or rdo will appear in the list box on the Data Tab of the Standard Report Expert.
  8. Continue creating your report normally. While creating your report, the ado or rdo specification will act like a database table, providing all fields that have been obtained from your ADO Recordset or RDO Resultset.


ADO and OLE DB

  1. Click the ADO and OLE DB option in the Select Data Source dialog box. This option is designed to allow you to specify an ADO connection string that can connect to any OLE DB provider.
  2. Type the ADO connection string into the text box provided, or click Build to open the Datal Links Properties dialog box. The following are examples of an acceptable connection string for ADO:

    DSN=Xtreme sample data;

    DATABASE=pubs;DSN=Publishers;UID=sa;Password=;

  3. Type in the first example shown here to follow along in this tutorial. Click Next in the Select Data Source dialog box when finished. The Select Recordset dialog box appears.
  4. Determine if you want to create a Recordset using an object available from your data source, such as a database table, or if you prefer to specify a SQL statement. Select the appropriate option in the Recordset section of the Select Recordset dialog box.
  5. If you want to connect to a database object, use the Object Type drop-down list to select the type of database object, such as a Table, then select the object itself from the Object drop-down list.
  6. If you want to obtain a Recordset using a SQL statement, write the SQL statement in the text box provided, or click Build to use the Microsoft Query application and Query Wizard to visually design your SQL statement.
  7. Click Finish in the Select Recordset dialog box. You will see ado in the list box on the Data Tab of the Standard Report Expert.
  8. Continue creating your report normally. While creating your report, the ado specification will act like a database table, providing all fields that have been obtained from your ADO Recordset.


DAO

  1. Click the DAO option in the Select Data Source dialog box. This option allows you to connect to a database file through Data Access Objects (DAO).
  2. Select a database type from the Database drop-down list box. This list displays all DAO compatible database drivers installed on your system. Crystal Reports installs many DAO drivers for you. For this example, you can select Access as the database type.
  3. Use the Browse button to open the Select Database File dialog box. Use this dialog box to locate and select a database file. Crystal Reports includes several sample databases in the \Program Files\Seagate Software\Crystal Reports directory by default. You can select the XTREME.MDB Access file from this directory for this example.
  4. Click Open in the Select Database File dialog box, and the path and file name of the database you selected appear in the DAO text box on the Select Data Source dialog box.
  5. Click Next, and the Select Recordset dialog box appears.
  6. If the database requires log on information, specify a user name and password to log on.
  7. Determine if you want to create a Recordset using an object available from your database, such as a database table, or if you prefer to specify a SQL statement. Select the appropriate option in the Recordset section of the Select Recordset dialog box.
  8. If you want to connect to a database object, use the Object Type drop-down list to select the type of database object, such as a Table, then select the object itself from the Object drop-down list.
  9. If you want to obtain a Recordset using a SQL statement, write the SQL statement in the text box provided and click Next.
  10. Click Finish in the Select Recordset dialog box. You will see dao in the list box on the Data Tab of the Standard Report Expert.
  11. Continue creating your report normally. While creating your report, the dao specification will act like a database table, providing all fields that have been obtained from your DAO Recordset.


Crystal Data Object

The Crystal Data Object (CDO) is an ActiveX data source that allows you to define fields and records at runtime based on data that exists only at runtime. Through CDO, any data can become a virtual database and can be reported on using the power of the Report Designer Component. The Crystal Data Object does not support Memo or Blob fields.

CDO, like DAO and ADO, is based on the Component Object Model (COM). Any development environment that supports COM interfaces can dynamically generate a set of data for a report without relying on a database that exists at design time.

Applications that produce data that does not exist outside of the running application have been unable, until now, to take advantage of the most powerful reporting features in the industry. CDO, however, solves that problem. For instance, applications that monitor system or network resources, or any constantly operating environment, can produce a current report on such information at any time. No longer does data need to be dumped to a separate database before analysis. Through CDO, the Active Data Driver, and the Report Designer Component, analysis is instant and up-to-date.

The following topics are discussed in this section:

  • CDO vs. the Crystal Data Source Type Library
  • Using the Crystal Data Object
  • Crystal Data Object Model


CDO vs. the Crystal Data Source Type Library

Crystal Reports also supports the Crystal Data Source Type Library, for implementing in a Visual Basic class definition. Crystal Data Source objects can also be passed to the Active Data Driver as ActiveX data sources. However, the Crystal Data Source Type Library exposes a complete COM interface that must be implemented in your class. CDO, on the other hand, provides a fast and simple method for producing an internal customized ActiveX data source.

If you need to implement a complete data source in your application that allows runtime movement through records and fields, or if you intend to implement your data source as a separate ActiveX component, consider using the Crystal Data Source Type Library. However, if you need to create a quick and simple means of storing a large amount of data in a convenient package for reporting on, and the data will remain inside the same application as the reporting functionality, then use Crystal Data Objects.


Using the Crystal Data Object

The Crystal Data Object is an ActiveX DLL that can be accessed from any Windows development environment that supports ActiveX. By creating a Rowset object, similar to a Recordset, and filling it with fields and data, you design a virtual database table that can be passed as an ActiveX data source to the Crystal Active Data Driver. The Crystal Data Object does not support Memo or Blob fields.

Once the CDO Rowset has been created, it can be used just like any other active data source such as DAO or ADO. Use a procedure, much like the procedure described in Using the Active Data Driver, to print, preview, or export a report at runtime that is based on the CDO data source. Simply replace the steps that explain how to pass a DAO Recordset to the Active Data Driver with appropriate steps for passing your CDO Rowset.

The rest of this section explains how to create a CDO Rowset in Visual Basic. However, as an ActiveX DLL, CDO can be used by any application development environment that supports ActiveX.

To create a CDO Rowset:

  • Obtain a CDO Rowset Object
  • Add Fields to the Rowset Object
  • Obtain Data as Rows
  • Add Rows to the Rowset Object

Use these steps as a guideline for creating your own CDO Rowsets for use with the Active Data Driver.


Obtain a CDO Rowset Object

As stated earlier, CDO is a standard automation server. A Rowset object can be obtained from CDO using the Visual Basic CreateObject function:

Public CDOSet As Object

Set CDOSet = CreateObject("CrystalDataObject.CrystalComObject")

This Rowset object is, essentially, equivalent to a Recordset object you might obtain from DAO or another active data source. It is the Rowset object that you eventually pass to the Active Data Driver.


Add Fields to the Rowset Object

Once you have a Rowset object, you need to define fields for the Rowset. These fields act as the virtual database fields. The field names you specify must match the field names specified in the data definition file. For more information on data definition files, see Creating Data Definition Files.

Fields are added to a CDO Rowset using the AddField method:

CDOSet.AddField "Order ID", vbString

CDOSet.AddField "Company Name", vbString

CDOSet.AddField "Order Date", vbDate

CDOSet.AddField "Order Amount", vbCurrency

This code adds four fields to the Rowset with the specified field names, and field types. The field types are based on constant values for the Variant data type. The constant names used here are from Visual Basic. For information on valid constant values, see the AddField method in the Crystal Data Source Object Models.


Obtain Data as Rows

Data to be added as rows in the Rowset can be collected in a two dimensional array. The first dimension indicates rows, while the second dimension specifies fields for each row. The number of possible fields indicated by the second dimension must not exceed the number of fields you added to the Rowset using the AddField method. For example, you might define an array such as this:

Dim Rows(11, 3) As Variant

This specifies an array named Rows that contains 12 rows (0 to 11) and 4 columns (0 to 3). Notice that the four fields are defined with the AddField method, so the 4 columns in the Rows array are also defined. In addition, room has been made for 12 rows or records. Finally, since each field holds a different type of data, the array is defined as a Variant type.

Note: If your Rowset contains only a single field, you can use a one dimensional array instead of two dimensional. The single dimension indicates the number of columns or fields in your Rowset.

Now that you have defined an array to hold data, you can begin adding values to the array. These array values will become the actual field values for the virtual database. Most likely, you will want to design a routine in your application that adds runtime data generated by your application into each cell of the array. The following code, however, demonstrates how you can explicitly add values to the array:

Rows(0, 0) = "1002"     'The first Order ID

Rows(0, 1) = "Cyclist's Trail Co."     'The first Company Name

Rows(0, 2) = #12/2/94#     'The first Order Date

Rows(0, 3) = 5060.2725     'The first Order Amount

From here, you could continue by adding a value to the first field of the second record, Rows (1, 0). You continue filling in data record by record and field by field. This technique, of course, requires a lot of code and is not very practical. Most real applications would contain a looping procedure that progressively filled in values for the array.


Add Rows to the Rowset Object

At this point, you have created a CDO Rowset object, added fields to the Rowset, and collected data in an array that will become part of a virtual runtime database. All that is left is to pass the data from the array to the Rowset object. This step is handled with a single method:

CDOSet.AddRows Rows

The AddRows method accepts a two-dimensional array containing the values you want added to the Rowset and, ultimately, added to a report file that is printed or exported. A one-dimensional array is used to add a single row with multiple fields.

Rows can be added to a CDO Rowset with multiple calls to the AddRows method. However, once you begin adding rows of data to a Rowset, you cannot add any new fields to the Rowset. Any call to AddFields after a successful call to AddRows will fail.

Once you finish populating your virtual database in the CDO Rowset object, you can pass this object as an active data source to the Active Data Driver using the SetDataSource method in the Report Designer Component Automation Server.For complete instructions on doing this, see Pass the Recordset to the Active Data Driver.


Crystal Data Object Model

Crystal Data Objects support several methods and properties that can be used to work with the Rowset object. The object model for CDO is completely defined and described in the section Crystal Data Source Object Models.


Crystal Data Source Type Library

The Crystal Data Source Type Library, like Crystal Data Objects, provides a means for designing customized data sources that can be reported off of using the Active Data Driver. Crystal Data Source, however, unlike CDO, is a type library with an interface that can be implemented in a standard Visual Basic class. Once implemented, the Crystal Data Source interface allows your data to be fully manipulated much like a standard Recordset object in ADO or DAO.

Note: The Crystal Data Source type library is designed for Visual Basic 5.0 or later.

If you simply need a quick means for packaging some data in a form that can easily be reported off of, you should consider using Crystal Data Objects. Crystal Data Source, on the other hand, is designed for developers who need more flexibility when working with custom data sources. Keep in mind, though, once you add the Crystal Data Source interface to your class, you must implement all methods and properties exposed by the interface.


Creating a new project and class

The Crystal Data Source interface can be implemented inside almost any type of application. You might want to create and internal data source, for instance, inside the same standard executable application that you are implementing the Report Designer Component or another of the Crystal Report development tools. See the "Visual Basic Solutions" chapter in the Crystal Reports Technical Reference Guide, or the Crystal Reports Developer's Help (CrystalDevHelp.chm) for more information on the other Crystal Reports development tools.. On the other hand, you could create an ActiveX DLL that did nothing except implement Crystal Data Source. Your ActiveX DLL then could work as a separate data source to be accessed from other applications, much like ADO, RDO, and DAO are used.

The following topics are discussed in this section:

  • When to use the Crystal Data Source Type Library
  • Creating a new project
  • Adding a class module to a project
  • Adding a Sub Main() procedure


When to use the Crystal Data Source Type Library

The Crystal Data Source interface, as stated before, is designed to allow developers to create full-fledged data sources that work much like the ADO Recordset object. In fact, the interface has been designed to support properties and methods with names identical to several corresponding properties and methods in the ADO Recordset object. Through your existing knowledge of ADO, you can quickly familiarize yourself with the Crystal Data Source interface.

If you are designing an application or component that must produce a fully featured data source with methods and properties for easily navigating through records and fields, Crystal Data Source is the ideal solution. Not only is the interface easy to learn and use, it also follows a Recordset standard currently being developed by Microsoft.


Creating a new project

For this tutorial, you will implement the Crystal Data Source interface in an ActiveX DLL that can be referenced by other applications. One such application may be a standard executable that uses the Active Data Driver with the Report Designer Component to produce reports based on this new ActiveX data source.

  1. With Visual Basic running, select New Project from the File menu. The New Project dialog box appears.
  2. Select ActiveX DLL from the New Project dialog box, and click OK. Your new ActiveX DLL project is created.
  3. Select Class1 in the Project window, and make sure the Properties window is displayed. To display the Properties window, press the F4 key or select Properties Window from the View menu.

Note: If you are not creating an ActiveX DLL, you may not have a class module in your project. See the next section, Adding a class module to a project.

  4. Change the value of the (Name) property for Class1 to MyDataSource.
  5. Select Project1 in the Project window, and change the value of the (Name) property for Project1 to MyDataSourcePrj.
  6. Save the project. Use MyDataSource as the name of the class file and the
    project file.


Adding a class module to a project

Since you are creating an ActiveX DLL, your project already contains a class module that we can use to implement the Crystal Data Source interface. However, if you are creating a project that does not automatically include a class module, such as a Standard EXE project, you will need to use the following steps.

  • From the Project menu, select Add Class Module. The Add Class Module dialog box appears.
  • Make sure Class Module is selected, and click Open. The new class module is added to your project, and the code window for the module appears.


Adding a Sub Main() procedure

Although a Sub Main() procedure is not required by ActiveX DLLs created in Visual Basic 5.0 or later, you may want to create a Sub Main() procedure to handle initialization processes. Developers working in Visual Basic 4.0 are required to add the Main subroutine to an Automation Server DLL project and specify that the project use Sub Main() as the entry point. If you are creating an ActiveX EXE in Visual Basic 4.0 or later, you should add the Sub Main() procedure to allow your code to determine if it is being started as a stand-alone application or as an out-of-process automation server.

The following steps demonstrate how to add a Sub Main() procedure in Visual Basic versions 5.0 and 6.0. If you add this procedure to the MyDataSource project, you can leave the procedure empty.

  • From the Project menu in Visual Basic, select Add Module. The New Module dialog box appears.
  • Leave the default Module type selected, and click Open. A new module, Module1, is added to your project.
  • In the code window for the new module, add the following code:

    Sub Main()
    End Sub


Adding the type library

The Crystal Data Source interface is a standard COM (Component Object Model) interface that is defined in a type library (.TLB) file. To implement the Crystal Data Source interface in your Visual Basic application, you must first add a reference to the type library, implement the interface in your class module with the Implements statement, and, finally, create code for each of the properties and methods defined by the interface.

The following topics are discussed in this section:

  • Adding a reference to the Crystal Data Source Type Library
  • Viewing in the Object Browser
  • Using Implements in the class declaration


Adding a reference to the Crystal Data Source Type Library

If this is the first time you are using the Crystal Data Source type library, you may need to tell Visual Basic where the type library is located before you can add a reference.

  1. From the Project menu, choose References.

    The References dialog box appears.

  2. Scroll through the Available References list to locate the CRDataSource 1.0 Type Library. If you find the reference, skip to step 6. Otherwise, continue with the next step.
  3. In the References dialog box, click the Browse button to locate the type library file.

    The Add Reference dialog box appears.

  4. Locate the CRSOURCE.TLB type library file in the same directory that you installed Crystal Reports. If you accepted the default directory when you installed the product, this directory will be C:\Program Files\Seagate Software\Crystal Reports.
  5. Select CRSOURCE.TLB, and click Open. CRDataSource 1.0 Type Library will now appear in the Available References list in the References dialog box.
  6. Place a check mark in the check box next to CRDataSource 1.0 Type Library if one does not appear already.
  7. Click OK to add the reference to your project.


Viewing in the Object Browser

Before continuing with the design of your ActiveX DLL project, it may be helpful to look at the object model provided by the Crystal Data Source interface.

  1. From the View menu, select Object Browser. The Object Browser appears.
  2. Switch the Object Browser to display just the CRDataSourceLib object library.

Notice that the Crystal Data Source interface contains a single object: CRDataSource. This object is similar to the Recordset object you would see if you added a reference to the Microsoft ActiveX Data Objects Recordset 2.0 Library to your project. This is also the object you would pass to the Active Data Driver (Page 306) when producing a report at runtime.

Take a moment to review the properties and methods provided by the CRDataSource object. Close the Object Browser when finished.


Using Implements in the class declaration

The next step is to add the Crystal Data Source interface to your class module.

  1. With the code window for the MyDataSource class module open, add the following code to the General Declarations section of the class.

    Implements CRDataSourceLib.CRDataSource

  2. Open the drop-down list of objects in the upper left of the code window. You will see a new object has been added to the list: CRDataSource.
  3. Select CRDataSource from the list of objects. A new Property Get procedure is added to the class module for the FieldCount property of the CRDataSource object. Remember that in COM interfaces, properties are actually implemented as Get and Let procedures. For more information, refer to your Visual Basic documentation.
  4. Open the drop-down list in the upper right of the class module code window. Notice that several procedures appear corresponding to the properties and methods of the Crystal Data Source interface. In fact, the properties and methods you saw in the Object Browser are the same properties and methods listed here in the code window.


Implementing the functions

Once you have added the Crystal Data Source interface to your class module, you must implement all of the properties and methods in the interface to successfully produce a data source that can be compiled into an ActiveX DLL and used with the Active Data Driver. The first step to implementing all of the properties and methods is to add procedures to your class for each of the Crystal Data Source procedures.


Adding procedures

When you selected the CRDataSource object in the object list in the previous section, you automatically added a procedure to the class for the FieldCount property. This property procedure appears in bold in the list of CRDataSource methods and properties to indicate that it has already been added.

  1. With the CRDataSource object selected in the code window, select Bookmark [Property Get] from the drop-down list in the upper right corner of the code window. A Property Get procedure appears in the class for the Bookmark property of CRDataSource.
  2. Repeat the process for the Property Let procedure of the Bookmark property. Keep in mind that Property Get procedures allow values to be retrieved from properties while Property Let procedures allow values to be assigned to properties.
  3. Continue selecting each of the property and method procedures listed so that a procedure appears in your class for every property and every method defined by the Crystal Data Source interface.
  4. Notice that each of the procedures has been defined as Private. For our ActiveX DLL to expose these properties and methods to other applications, we need to change these to Public. Replace each Private statement with Public.
  5. Save your project to preserve all changes up to this point.


Implementing procedures

Exactly how you implement each of the properties and methods in the CRDDataSource interface depends upon the purpose and design of your application or component. To give you an idea of how to implement the procedures, though, the following code sample simply uses an ADO Recordset object connected to the Xtreme sample data DataSource. Obviously, this example has little value in a real application; an ADO Recordset can itself be reported on through the Active Data Driver. However, the example does illustrate how the properties and methods in the Crystal Data Source interface work.

Implements CRDataSourceLib.CRDataSource

Dim adoRs As ADOR.Recordset
Private Sub Class_Initialize()

    Set adoRs = New ADOR.Recordset

    adoRs.Open "Customer", "Xtreme sample data", _

        adOpenKeyset, adLockOptimistic, adCmdTable

End Sub
Private Sub Class_Terminate()

    adoRs.Close

    Set adoRs = Nothing

End Sub
Public Property Let CRDataSource_Bookmark(ByVal RHS As Variant)

    adoRs.Bookmark = RHS

End Property
Public Property Get CRDataSource_Bookmark() As Variant

    CRDataSource_Bookmark = adoRs.Bookmark

End Property
Public Property Get CRDataSource_EOF() As Boolean

    CRDataSource_EOF = adoRs.EOF

End Property
Public Property Get CRDataSource_FieldCount() As Integer

    CRDataSource_FieldCount = adoRs.Fields.Count

End Property
Public Property Get CRDataSource_FieldName _

    (ByVal FieldIndex As Integer) As String

    CRDataSource_FieldName = adoRs.Fields(FieldIndex).Name

End Property
Public Property Get CRDataSource_FieldType _

    (ByVal FieldIndex As Integer) As Integer

    CRDataSource_FieldType = adoRs.Fields(FieldIndex).Type

End Property
Public Property Get CRDataSource_FieldValue _

    (ByVal FieldIndex As Integer) As Variant

    CRDataSource_FieldValue = adoRs.Fields(FieldIndex).Value

End Property
Public Sub CRDataSource_MoveFirst()

    adoRs.MoveFirst

End Sub
Public Sub CRDataSource_MoveNext()

    adoRs.MoveNext

End Sub
Private Property Get CRDataSource_RecordCount() As Long

    CRDataSource_RecordCount = adoRs.RecordCount

End Property


Compiling the ActiveX DLL

Once you have finished implementing all of the properties and methods, you can compile the ActiveX DLL. When compiling ActiveX components, Visual Basic registers the component in the Windows Registry database. The name of the project, MyDataSourcePrj in this case, is used as the name of the component. The name of the class module, MyDataSource for this example, becomes the name of a creatable object. Once compiled, the component can be referenced by another application.

  1. Make sure you save the entire project so that all source code is preserved.
  2. From the File menu, choose Make MyDataSource.dll. Note that the name of the DLL that will be created is based on the name of your Visual Basic project file (.VBP), not on the project name as specified by the (Name) property.
  3. When the Make Project dialog box appears, select the location where the new DLL should reside.
  4. Click OK, and the new DLL is created and registered.


Passing the CRDataSource object to the Active Data Driver

Using an object that implements the Crystal Data Source interface is a straightforward process, much like using any ActiveX component in an application. A Reference to the component must first be made, then an instance of the component object must be created in the application, and finally, the properties and methods of the object can be used. In this example, we will use the ActiveX DLL we created to obtain a MyDataSource object that we can pass to the Active Data Driver in a report generated using the Crystal Designer Component.

For this example, we will assume you have created an application in Visual Basic and designed a report using the Crystal Report Designer Component. For more information on the Crystal Report Designer Component, see the Crystal Reports Developer's Guide.

If you want to create a new report that can use the MyDataSource ActiveX DLL, create the report using three fields corresponding to the Customer ID, Customer Name, and City fields in the Customer table of the Xtreme sample data ODBC data source. To make things simple, you can use ADO to connect directly to those three fields. The purpose of this tutorial is simply to teach the techniques, not, necessarily, to produce a real application.


Adding a reference to MyDataSourcePrj

With your application open in Visual Basic:

  1. Choose References from the Project menu. The References dialog box appears.
  2. Scroll through the list of Available References to locate the MyDataSourcePrj component.
  3. Add a check mark to the check box next to MyDataSourcePrj, and click OK. The component is now available to your application.
  4. Open the Object Browser in Visual Basic, and select the MyDataSourcePrj library. Notice that the MyDataSource object is available and that this object contains all of the properties and methods that you implemented in the MyDataSource ActiveX DLL. Additionally, each of these properties and methods corresponds to a property or method in CRDataSource.


Creating an instance of MyDataSource

This section assumes you are already familiar with how to pass a new data source to the Active Data Driver at runtime. If you need more information on using the Active Data Driver, refer to Active Data Driver. The following steps simply illustrate how to assign the myDs object created above to the Active Data Driver so that a report will use it as the source of data at runtime.

To actually use the MyDataSourcePrj component, you must create an instance of the MyDataSource object, then assign that object to the Report object displayed by your application. Assuming you created a report in your application using the Crystal Designer Component and accepted default settings for adding the Crystal Report Viewer/ActiveX to your project:

  1. Open the code window for the form containing the CrystalReport Viewer/ActiveX.
  2. In the General Declarations section for the form, add the following code:

    Dim myDs As New MyDataSourcePrj.MyDataSource

  3. In the Form_Load procedure, add the following line before the Report object is assigned to the ReportSource property of the CRViewer1 object:

    CRXReport.Database.SetDataSource myDs,3, 1

Note: This example is based on a Visual Basic application created using the Report Designer Component. for more information see Report Designer Component Object Model.

The first line of code creates an instance of the MyDataSource object in your application, much like you might create an instance of an ADO Recordset object. The second line of code added uses the SetDataSource method inside the Crystal Designer Component library to dynamically change the source of data used by your report.

If you designed your report using an ADO, DAO, or RDO data source, or by using a Data Definition file, then your report uses the Active Data Driver to access the report data at runtime. Since the Active Data Driver also supports data sources that expose the Crystal Data Source interface, you can easily assign the MyDataSource object to your report.


Crystal Data Source Projects

Now that you have seen the extensive power of the Crystal Data Source interface implemented inside a Visual Basic class, you can begin to consider the extensive possibilities for its use. Many computer based operations produce continuous streams of data in real-time. In your own work, you may encounter needs for gathering data from process control systems, data acquisition applications, or computer-based instrumentation.

In these kinds of applications, data is usually gathered and stored for later analysis. Systems running in real-time, however, may need real-time monitoring and reporting. With objects that implement the Crystal Data Source interface, you can gather and move through data as it is generated, then produce up to the instant analysis through reports.

Programmer's building n-tier applications that operate across a network may often find themselves designing business objects and other business rules components. By implementing the Crystal Data Source interface in business object components, you can design reports that produce real-time information about data traveling across the network. Even Microsoft Transaction Server components can implement a fully functional ActiveX data source for reporting. Crystal Data Source takes your applications from runtime to real time.


Crystal Data Source Object Models

Crystal Reports provides support for reporting off data when no true data source exists. In this section you will find detailed information, including properties and methods, on Crystal Data Objects and the Crystal Data Source Type Library.

Click the appropriate link to jump to that section:

  • Crystal Data Source Object Models
  • Crystal Data Objects
  • CrystalComObject
  • Crystal Data Source Type Library


Crystal Data Source Object Models

Crystal Reports includes two ActiveX based data source models to allow on-the-fly reporting when a true data source does not exist at design time, and the data at runtime does not exist in a relational or OLAP database. The Crystal Data Sources allow you to dynamically produce data at runtime inside your code, then pass the data to an existing report file. Both data source models are designed primarily for Visual Basic programmers, but they can be used within other development environments that support ActiveX components and interfaces.


Crystal Data Objects

Crystal Data Objects allow you to quickly design a set of relational data at runtime using standard Visual Basic arrays. For more information on using Crystal Data Objects in Visual Basic, see Crystal Data Object. To add a reference to the Crystal Data Objects component to your Visual Basic application, select the Crystal Data Object item in the Available References list box of the References dialog box. Crystal Data Objects do not support Memo or Blob fields.


CrystalComObject

The CDO component provides a single object named CrystalComObject. This object works much like a Recordset or Rowset that you might use in ADO, DAO, or RDO. Rather than connecting to an existing database, though, CDO allows you to fill it with data stored in a standard Visual Basic array. Once filled with data, the entire object can be passed to the Grid Controls and the Crystal Report Engine at runtime, producing a dynamic report filled with data only available at runtime.

To create an instance of the CrystalComObject in Visual Basic, use the following code as an example:

Dim cdoRowset As Object

Set cdoRowset = CreateObject("CrystalComObject.CrystalDataObject")

The following topics are discussed in this section:

  • CrystalComObject Properties
  • CrystalComObject Methods


CrystalComObject Properties

The CrystalComObject provides a single property:

RowCount

Use this property to obtain the number of rows in the rowset once data has been assigned. This is especially useful if data is added to the Rowset in several steps, each step adding more to the size of the Rowset. This value can be used to find out how many rows have been added.

Example
Dim numRows As Long

numRows = cdoRowset.RowCount


CrystalComObject Methods

The CrystalComObject uses the following methods. These methods each have a section describing their parameters and returns, followed by an example.

  • AddField
  • AddRows
  • DeleteField
  • GetColCount
  • getEOF
  • GetFieldData
  • GetFieldName
  • GetFieldType
  • MoveFirst
  • MoveNext
  • MoveTo
  • Reset


AddField

Function AddField(FieldName As String, [FieldType]) As Boolean

Use this method to add fields to a rowset before adding data. The rowset must have fields defined before data can be added using the AddRows method.

Parameters

FieldName
A string value specifying the name of the field.

FieldType
An optional value specifying the data type that will be contained in this field. Use Visual Basic VarType constants to specify the data type. If this value is omitted, the vbVariant type will be used.

Returns

A Boolean value indicating whether or not the field was successfully added to the Rowset.

Example
cdoRowset.AddField "Order ID", vbString

cdoRowset.AddField "Company Name", vbString

cdoRowset.AddField "Order Amount", vbCurrency


AddRows

Sub AddRows(RowData)

Use this method to assign an array of data to the CDO Rowset.

Parameters

RowData
A standard Visual Basic two-dimensional array. The first dimension specifies the number of rows in the Rowset, while the second dimension specifies the number of fields for each row. A one-dimensional array is used to add a single row with multiple fields. When this array is dimensioned, it must be defined As Variant. For example:

Dim Rows(11, 3) As Variant

This example creates an array that will hold 12 rows with 4 fields. You must assign data to all cells in the array before assigning the array to the Rowset using AddRows.

Example

cdoRowset.AddRows Rows


DeleteField

Function DeleteField(FieldName As String) As Boolean

This method removes an existing field from the Rowset. If the field contains any data, that data is lost.

Parameters

FieldName
The name of the field you want to delete from the Rowset.

Returns

A Boolean value indicating whether or not the field was successfully deleted. If the field does not exist, this function will return False.

Example

cdoRowset.DeleteField "Company Name"


GetColCount

Function GetColCount() As Integer

This function returns the number of columns or fields currently in the Rowset.

Returns

An integer value indicating the number of fields in the Rowset.

Example
Dim numFields As Integer

numFields = cdoRowset.GetColCount


getEOF

Function getEOF() As Boolean

Use this function to determine if the current row in the Rowset is the last row.

Returns

True if the current row is the last row in the Rowset. False if the current row is anywhere else in the Rowset.

Example
If cdoRowset.getEOF Then

    cdoRowset.MoveFirst

End If


GetFieldData

Function GetFieldData(column As Integer)

This method obtains the current value of a specific column in the Rowset for the currently selected row.

Parameters

column
A number indicating which field (column) of the row you want the current value of. Rowset columns, like array dimensions, are 0 based. The first column is 0, the second is 1, etc.

Returns

A variant value that contains the data for the specified field of the current row.

Example
Dim fieldData As Variant

fieldData = cdoRowset.GetFieldData 0


GetFieldName

Function GetFieldName(column As Integer) As String

Returns the name of the specified field (column). Field names are assigned using AddField.

Parameters

column
A number indicating which field (column) of the Rowset you want the name of. Rowset columns, like array dimensions, are 0 based. The first column is 0, the second is 1, etc.

Returns

A string containing the name of the specified field.

Example
Dim secondField As String

secondField = cdoRowset.GetFieldName 1


GetFieldType

Function GetFieldType(Field) As Integer

Use this method to obtain the type of data contained by a field in the Rowset. Data types are assigned to fields using AddField.

Parameter

Field
This parameter indicates which field you are querying for the type of data contained. This field can accept either a numeric value or a string value. If you use a numeric value, it must be a number representing the field (column) of the Rowset you want to find out the data type of. Rowset columns, like array dimensions, are 0 based. The first column is 0, the second is 1, etc. If a string is used, the string must contain the name of the field.

Returns

A Visual Basic VarType constant indicating the type of data contained in the field.

Example
Dim dataType As Integer

dataType = cdoRowset.GetFieldType "Customer Id"

If dataType = vbString Then

    ' Do something with the string

End If


MoveFirst

Function MoveFirst() As Boolean

This method moves to the first row (record) in the Rowset.

Returns

A Boolean value indicating whether or not the current row was successfully set to the first row. If the Rowset contains no data, this method will return False.

Example

cdoRowset.MoveFirst


MoveNext

Function MoveNext() As Boolean

Moves to the next row (record) in the Rowset. The current record is set to the new row.

Returns

A Boolean value indicating whether or not the current record was successfully set to the next row in the Rowset. This function will return False if the current record before calling the method is the last row of the Rowset.

Example

cdoRowset.MoveNext


MoveTo

Function MoveTo(recordNum As Long) As Boolean

Moves the current record to the specified record number in the Rowset.

Parameter

recordNum
A 1-based value indicating to which record in the Rowset you want to move. The first record is 1, the second is 2, etc.

Returns

A Boolean value indicating whether or not the current record was successfully set to the specified record number. This method returns False is the specified record does not exist.

Example

cdoRowset.MoveTo 9


Reset

Sub Reset()

Resets the Rowset, clearing all fields and data.

Example

cdoRowset.Reset


Crystal Data Source Type Library

The Crystal Data Source Type Library is a COM interface type library that can be implemented in your own Visual Basic classes. One the interface has been added to a class, you must implement every method and property defined by the interface. This process requires extensive Visual Basic coding, but the result is a complete data source that can be used much like other ActiveX data sources such as ADO or DAO. Additionally, a data source defined using the Crystal Data Source Type Library can be passed to report files at runtime through the Grid Controls and the Crystal Report Engine, allowing dynamic runtime reporting on powerful customized data sources.

Possible uses for data sources defined using the Crystal Data Source Type Library are ActiveX style data sources, similar to ADO, DAO, and RDO, Business Objects and business rules components, Microsoft Transaction Server components, or instrumentation systems that produce dynamic real-time data.

Note that as a type library, the Crystal Data Source Type Library does not actually provide any functionality on its own. You must determine the actual functionality by implementing each of the properties and methods defined in the type library interface. The descriptions given here of the CRDataSource object, its properties, and its methods are intended as a guideline for the type of functionality you should define in your own classes.


CRDataSource

CRDataSource is a COM interface rather than an actual COM object. By writing code for each of the CRDataSource methods and properties in your own code, your class or COM component implements the CRDataSource interface and, therefore, becomes the actual Crystal Data Source.

To implement CRDataSource in a Visual Basic class, use the following code in the General Declarations section of your class module:

Implements CRDataSourceLib.CRDataSource

Once implemented, CRDataSource will appear as an available object in your class module. You must add code for every property and method of the CRDataSource object to correctly implement the Crystal Data Source interface. For more information, see Crystal Data Source Type Library.

The following topics are discussed in this section:

  • CRDataSource Properties
  • CRDataSource Methods


CRDataSource Properties

The Crystal Data Source interface defines the following properties. An example of each property follows the property description.

  • Bookmark
  • EOF
  • FieldCount
  • FieldName
  • FieldType
  • FieldValue
  • RecordCount


CRDataSource Methods

The Crystal Data Source type library defines the following two methods:

MoveFirst

MoveNext


Bookmark

Used to obtain a bookmark (identifier) for a particular record in the Recordset, or to move to the record identified by the bookmark. To simplify the process of navigating to a particular record over and over again, you can save a bookmark for the record in a variable, then quickly return to that record by assigning the value of the variable to the Bookmark property.

Example
Dim aBookmark As Variant

aBookmark = myCRDataSource.CRDataSource_Bookmark
' Move around in the Recordset performing various operations
' To return to the bookmarked record:

myCRDataSource.CRDataSource_Bookmark = aBookmark


EOF

Read only.

This property indicates whether or not the current record is the last record in the Recordset. The value of the EOF property is True if the current record is the last record, False otherwise.

Example
If myCRDataSource.CRDataSource_EOF = True Then

    myCRDataSource.CRDataSOurce_MoveFirst

End If


FieldCount

Read only.

This property returns the number of fields in the Recordset.

Example
Dim numFields as Integer

numFields = myCRDataSource.CRDataSource_FieldCount


FieldName

Read only.

Returns the name of a specific field as indicated by the field index. Field indexes for the Crystal Data Source interface start with 1 for the first field, 2 for the second, etc.

Example
Dim firstField As String

Dim secondField As String

firstField = myCRDataSource.CRDataSource_FieldName 1

secondField = myCRDataSource.CRDataSource_FieldName 2


FieldType

Read only.

Obtains a Visual Basic VarType constant indicating the type of data stored in a particular field. Fields are identified using field indexes. Field indexes for the Crystal Data Source interface start with 1 for the first field, 2 for the second, etc.

Example
Dim fieldType As Integer

fieldType = myCRDataSource.CRDataSource_FieldType 1

If fieldType = vbString Then

    ' Do something with the string data in this field

End If


FieldValue

Obtains the data actually stored in the field for the current record. Fields are identified using field indexes. Field indexes for the Crystal Data Source interface start with 1 for the first field, 2 for the second, etc.

Example
Dim fieldVal As Variant

fieldVal = myCRDataSource.CRDataSource_FieldValue 2


RecordCount

Read only.

This property contains the total number of records in the Crystal Data Source recordset.

Example
Dim numRecords as Long

numRecords = myCRDataSource.CRDataSource_RecordCount


MoveFirst

Sub MoveFirst()

Moves to the first record in the Recordset. The first record is set as the current record.

Example

myCRDataSource.CRDataSource_MoveFirst


MoveNext

Sub MoveNext()

Moves to the next record in the Recordset and sets that record to the current record. A Visual Basic error occurs if the current record before calling this method is the last record. Use EOF to determine if the current record is the last record in the recordset.

Example
If Not myCRDataSource.CRDataSource_EOF Then

    myCRDataSource.CRDataSource_MoveNext

End If


The Crystal Active Data Driver Reference

This section provides information on the functions available in the Active Data Driver (P2smon.dll). These functions simplify the creation of Data Definition Files and allow you to pass a recordset to a report using the Crystal Report Print Engine.

Click the appropriate link to jump to that section:

  • Overview


Overview

The Crystal Active Data Driver provides functions that can be called from your application to simplify the process of designing field definition files and reports at runtime. In addition, a function is provided that translates a Visual Basic object type, such as a Recordset object, into a string value that can be used with the PEGetNthTableLocation function in the Report Engine API.

Declarations of these functions are provided in both C and Visual Basic syntax. If you are using a language other than C, C++, or Visual Basic, refer to the documentation for your development environment for instructions on how to translate C declare statements.

The following topics are discussed in this section:
  • CreateFieldDefFile
  • CreateReportOnRuntimeDS
  • SetActiveDataSource


CreateFieldDefFile

Creates a tab-separated text file, known as a field definition file, which represents the structure of the data in a specified Recordset or Rowset object. This field definition file can then be used to design a report file using the Runtime DB option in the Create Report Expert of Crystal Reports. When designing an application that prints, previews, or exports the report, the field definition file can be replaced, at runtime, by the Recordset or Rowset object.

C Syntax
BOOL FAR PASCAL CreateFieldDefFile(LPUNKNOWN FAR *lpUnk,

                    LPCSTR fileName,

                    BOOL bOverWriteExistingFile);
Visual Basic Syntax
Declare Function CreateFieldDefFile Lib "p2smon.dll"(lpUnk As Object, _

    ByVal fileName As String, ByVal bOverWriteExistingFile As Long) _

    As Long
Parameters

Parameter | Description
lpUnk | The active data source used to create the field definition file. In C or C++, this is a pointer to an Iunknown derived COM interface relating to a DAO or ADO Recordset. In Visual Basic, this is a Recordset or Rowset object.
fileName | The path and file name of the field definition file to be created.
bOverWriteExistingFile | If a field definition file already exists with the specified path and file name, this flag indicates whether or not to overwrite that file.

Return Value

Returns 0 (False) if the call failed. Returns 1 (True) if the call succeeded and the field definition file was created.

Remarks

This function creates a field definition file only, and does not create a report file. You must create a report file using Crystal Reports.


CreateReportOnRuntimeDS

Creates a tab-separated text file, known as a field definition file, which represents the structure of the data in a specified Recordset or Rowset object. Then, the function creates a blank report file based on this field definition file. When designing an application that prints, previews, or exports the report, the field definition file can be replaced by the Recordset or Rowset in the active data source.

C Syntax
BOOL FAR PASCAL CreateReportOnRuntimeDS(LPUNKNOWN FAR *lpUnk,

                        LPCSTR reportFile,

                        LPCSTR fieldDefFile,

                        BOOL bOverWriteFile,

                        BOOL bLaunchDesigner);
Visual Basic Syntax
Declare Function CreateReportOnRuntimeDS Lib "p2smon.dll" ( _

    lpUnk As Object, ByVal reportFile As String, ByVal fieldDefFile _

    As String, ByVal bOverWriteFile As Long, ByVal bLaunchDesigner _

    As Long) As Long
Parameters

Parameter | Description
lpUnk | The active data source used to create the field definition file. In C or C++, this is a pointer to an Unknown derived COM interface relating to a DAO or ADO Recordset. In Visual Basic, this is a Recordset or Rowset object.
reportFile | The path and file name of the report file to be created.
fieldDefFile | The path and file name of the field definition file to be created.
bOverWriteFile | If a field definition file already exists with the specified path and file name, this flag indicates whether or not to overwrite that file.
bLaunchDesigner | If True (1), Crystal Reports is launched with the newly created report file opened. Crystal Reports must be installed on the system.

Return Value

Returns 0 (False) if the call failed. Returns 1 (True) if the call succeeded and the field definition file was created.

Remarks

This function creates a field definition file, then creates a report file based on that field definition file. The function CreateFieldDefFile, is unnecessary when this function is used.


SetActiveDataSource

The SetActiveDataSource Function is used to provide information about a data source to the Crystal Active Data database driver. For instance, if a report has been designed using the Crystal Active Data Driver this method can be used to provide an active data source for the report, such as a DAO, ADO, or RDO recordset or a CDO rowset. In this case, the object passed to the third parameter of this function replaces, at runtime, the field definition file used to create the report.

Visual Basic Syntax
Declare Function SetActiveDataSource Lib "p2smon.dll" (ByVal printJob as
Integer,

                                 ByVal tableNum as Integer,

                                  x as Object) As Long
Parameters

Parameter | Description
printJob | Specifies the print job to which you want to add the active data source.
tableNum | The 0 based number of a table for which you want to pass the active data recordset or rowset.
x | Variant data passed to the database driver such as a DAO, ADO or RDO recordset or a CDO rowset.

Return Value

Returns 0 (False) if the call failed. Returns 1 (True) if the call succeeded the data source was passed.

Remarks

The SetActiveDataSource function is used in conjunction with the Crystal Report Print Engine (Crpe32.dll) in a Visual Basic application. If you are using Visual C++ see PESetNthTablePrivateInfo.


International Office Directory

This appendix provides contact information by region. For technical support information, see the Technical Support Guide.


International Office Directory

The following section lists the contact information for Sales and Product Support at each Seagate Software office, worldwide.

For more information, visit our web site at http://www.seagatesoftware.com.

  • North and South American Offices
  • Asia/Pacific Offices
  • Europe
  • Africa and Middle East


North and South American Offices

Canada and USA - North & South American Head Office

Seagate Software
840 Cambie Street
Vancouver, BC V6B 4J2
Canada

Sales and General Inquiries

Telephone: 604 681 3435

Toll-Free: 1 800 877 2340

Fax: 604 681 2934


Latin America

Sales and General Inquiries

Telephone: 604 681 3435

Fax: 604 681 2934


Asia/Pacific Offices

Australia

Seagate Software Pty Ltd.
Level 9, 52 Alfred Street
Milsons Point, NSW 2061
Australia

Sales and General Inquiries

Telephone: +61 2 9955 4088

Fax: +61 2 9955 7682


Hong Kong

Seagate Software (HK)
Suite 2603, 26th Floor
Universal Trade Center
3 Arbuthnot Road, Central
Hong Kong

Sales and General Inquiries

Telephone: +852 2575 2576

Fax: +852 2893 2727


Japan

Seagate Software
3F, Bridgestone Bldg
2-13-12 Hirakawa-cho,
Chiyoda-ku
Tokyo 102-0093

Sales and General Inquiries

Telephone: +81 3 5226 3601

Fax:+81 3 5226 3606

Email: sales_jp@img.seagatesoftware.com


Malaysia

Seagate Software
(a subsidiary of Seagate Technology)
Level 36 Menara Citibank
165 Jalan Ampang
Kuala Lumpur 50450
Malaysia

Sales and General Inquiries

Telephone: 603 2169-6307 or 603-2169-6308

Fax: 603-2169-6168

Email : southasia@seagatesoftware.com


Singapore

Seagate Software
14 Science Park Drive
#03-02 The Maxwell
Singapore Science Park
118226 Singapore

Sales and General Inquiries

Telephone: +65 777 0533

Fax: +65 777 8786


Europe

United Kingdom - EMEA and Northern European Head Office

Seagate Software
The Broadwalk
54 The Broadway
Ealing,
London, W5 5JN
United Kingdom

Seagate Software
St. Matthews Court
4 Civic Drive
Ipswich, Suffolk, 1P1-2QA
United Kingdom

Sales and General Inquiries

Telephone: +44 (0) 208 566 2020

Fax: +44 (0) 208 231 0600


Austria

Seagate Software
Frankfurter-Str. 21-25
D-65760 Eschborn
Germany

Sales and General Inquiries

Telephone: +49 (0) 69 9509 6310

Fax: +49 (0) 69 9509 6314


Belgium

Seagate Software
62 bis, Avenue Andre Morizet
Boulogne-Billancourt Cedex
Paris, F-92643
France

Sales and General Inquiries

Telephone: +33 (0) 155 174 082

Fax: +33 (0) 155 174 086


France - SEMEA. Southern Europe and Middle East Head Office

Seagate Software
62 bis, Avenue Andre Morizet
Boulogne-Billancourt Cedex
Paris, 92643
France

Sales and General Inquiries

Telephone: +33 (0) 155 174 082
or: +33 (0) 1 41 10 16 00

Fax: +33 (0) 155 174 086
or: +33 (0) 1 41 10 16 57

Germany - Central European Head Office

Seagate Software GmbH
Frankfurter-Str. 21-25
D-65760 Eschborn
Germany

Sales and General Inquiries

Telephone: +49 (0) 69 95 09 63 10

Fax: +49 (0) 69 95 09 63 14


Ireland

The Broadwalk
54 The Broadway
Ealing, London
W5 5JN England

Sales and General Inquiries

Telephone: +44 (0) 208 566 2020

Fax: +44 (020) 208 231 0600


Italy

Seagate Software
Via Conservatorio 22
20122 Milano
Italy

Sales and General Inquiries

Telephone: +39 027 729 310

Fax: +39 02 772 940

Netherlands

Seagate Software
Hojel City Centre
GebouwD, 4e etage
Graadt Van Roggenweg 328
Postbox 19127

3501 DC Utrecht
Netherlands

Sales and General Inquiries

Telephone: +44 (0) 208 566 2020

Fax: +44 (0) 208 231 0600


Spain

Seagate Software
Paseo de la Castellana 93-4a
28046, Madrid
Spain

Sales and General Inquiries

Telephone: +34 91 555 5198

Fax: +34 915 559 957


Sweden

Seagate Software
Kanalvagen 10C
Upplands Vasby
194 61 Sweden

Sales and General Inquiries

Telephone: +46 (0) 858 771 171

Fax: + 46 (0) 858 771 172


Switzerland

Seagate Software
World Trade Centre
PO Box 112
Leutschenbachstrasse 95
CH-8050 Zurich
Switzerland

Sales and General Inquiries

Telephone: +41 1 308 3922

Fax: +41 1 308 3500


Africa and Middle East

South Africa

Seagate Software
Sandown Village Office Park
East Court
1 Gwen Lane cnr Maude Street
Sandton 2146
South Africa

Postal Address

Seagate Software
PO Box 78720
Sandton 2146
Republic of South Africa

Sales and General Inquiries

Telephone: +27 11 3059700

Fax: +27 11 3059702


Welcome_Dev_Help.html

Seagate Software IMG Holdings, Inc.
http://www.seagatesoftware.com
Support services:
http://support.seagatesoftware.com